开发者

Filtering results based on a many-to-many relationship

Posts belong to Users. Users have and belong to many roles (i.e., the tables we're dealing with here are posts, users, roles, and roles_users)

How can I select all posts written by a user who ha开发者_运维技巧s the "Editor" role?

I.e., I want the database-driven version of

Post.all.select{|p| p.user.roles.map(&:name).include?("Editor")}}


Post.all(:joins => {:user => :roles}, :conditions => ["roles.name = ?", "editor"])


You could try something like this:

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :posts, :through => :users
end

Then you can do something like this:

Role.find(editor_id).posts
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜