I have a user model, User.rb.
Now I have a table that looks like:
user_something
user_id
something_id
something_type
The value of something_type comes from a enumeration I have in my rails code. The something_id can be an id from many other tables, meaning it represenets the id of lots of db tables, and the something_type will tell me if it is an article, or whatever.
So now 开发者_Python百科say on my Article.rb model, I want to create an association to the user_something table, which will list all rows where the something_type = 3, and the something_id = article_id.
select * from user_something where something_type = 3 and something_id = xxx
The query would have to inner join with the users table to get me a collection of Users.
How can I do this?
You want to use a polymorphic association
Something like:
class User
belongs_to :somethingable, :polymorphic=>true
end
class OtherClass
has_many :users, :as => :somethingable
end
class YetAnotherClass
has_many :users, :as => :somethingable
end
精彩评论