开发者

How to handle this model association based on a enumeration?

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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜