lala
lala

Reputation: 2082

Rails database query with conditions from two tables?

I have these models:

class Post
  belongs_to :user
end

class User
  has_many :posts
end

I want to get the post with the title 'Some Title' by any guest user (i.e. user.role == 'guest').

The title will be unique among guest users, but it is possible that some non-guest user has a post with that title. I'm trying to use the Rails guide and the Api, but I can't seem to put the right syntax together.

I hoped it was as simple as User.where(:role => 'guest').posts.find_by_title('some title'), but that throws undefined method `posts' for #ActiveRecord::Relation:0x4e6d380.

Post.find_by_title('some title', :conditions => {:users => {:role => 'guest'}, :joins => :users} throws PG::Error: ERROR: missing FROM-clause entry for table "users".

Anything with Post.joins(:users) throws Association named 'users' was not found.

Upvotes: 1

Views: 106

Answers (2)

MurifoX
MurifoX

Reputation: 15089

Read about using ActiveRecord method .joins, that generates SQL joins.

User.joins(:posts).where("users.role = ? AND posts.title = ?", 'guest', 'some title')

Upvotes: 2

Bob McCown
Bob McCown

Reputation: 127

Try Post.joins(:user) (not :users) on the joins.

Upvotes: 1

Related Questions