views:

32

answers:

2

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 has the "Editor" role?

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

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

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
jigfox
+1  A: 
Post.all(:joins => {:user => :roles}, :conditions => ["roles.name = ?", "editor"])
Geoff Lanotte
This is correct, though `roles.name => ?` should be `roles.name = ?`
Horace Loeb
good call, updated the post. Thanks!
Geoff Lanotte