xxyyxx
xxyyxx

Reputation: 2396

ActiveRecord query with two associated models

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.

Upvotes: 1

Views: 1243

Answers (3)

pricey
pricey

Reputation: 166

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.

Upvotes: 1

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

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

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

Upvotes: 3

tw airball
tw airball

Reputation: 1359

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.

Upvotes: 1

Related Questions