1

I have two models, Deal and User. A user has_many deals, and a deal belongs_to a user (the user who created the deal). Users have the attribute roles, where user.roles is an array.

I want to find all deals that were created by users whose roles include "developer". I'm used to writing SQL for database queries, so I'm having trouble here.

3 Answers 3

3
@deals = Deal.joins(:users).where(:users => { :roles => ['developer'] })

Reference: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

1
  • Hm, I seem to be getting this error when trying this in the rails console: "ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'user.roles' in 'w here clause': SELECT deals.* FROM deals INNER JOIN users ON users.id = deals.user_id WHERE user.roles IN ('developer')"
    – xxyyxx
    Apr 11, 2013 at 15:17
1

A couple of options:

@deals = Deal.select{|d| d.user.roles.include?("developer")}

Or

@deals = User.select{|u| u.roles.include?("developer")}.map(&:deals).flatten

I prefer the first one, but the second one may be quicker depending on how many deals and users you have.

1

I think of myself as a sql caveman, but you can do something like: Deal.includes(:users).where(:users => {:role => 'developer'}) or however your user roles are queried.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.