开发者

Find all records of a certain type in Polymorphic table using ActiveRecord in Rails 3

I have a table Category that is a polymorphic model for a bunch of other models. For instance

model Address has shipping, billing, home, work category

model Phone has home, mobile, work, fax category

model Product has medical, it equipment, automotive, aerospace, etc categories.

What I want to be able to do is something like

Product.all_categories and get and array of all categories that are specific to this model.

Of course I can do something like this for each model in question:

Category.select("name").where("categorizable_type 开发者_开发知识库= ?","address")

Also pace_car - which is rails 3 ready, allows me to do something like this:

Category.for_category_type(Address)

But I was wondering if there is a more straightforward / elegant solution to this problem using Active Record iteself - without relying on a gem?

Thank you


I'm not aware of anything built-in to ActiveRecord to give you this, but you could set up that for_category_type method in one line of code in your Category controller:

scope :for_category_type, lambda { |class_name| where("categorizable_type = ?", class_name) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜