ruby - Having issues building a rails query that includes three associated models -
i have 3 models i'm working with: user
, deal
, , investment
.
user
user has many :deals user has many :investments
deal
deal has many :investments deal belongs :user
investment
investment belongs :user investment belongs :deal
(these associations have set between these models)
lets have user record 'u', , deal has attribute called funding_type_id
.
i want find investments made user 'u' investment.deal.funding_type_id == 3
.
or more clear: investments made on deal user. set of investments made user 'u' on deals who's funding type id 3.
i posted awhile ago, didn't receive successful responses. i've made several attempts on own since then, have been met failure, i'm so. explained question clearly. thanks!
edit: bad, misread question -- morning after late night :)
try instead:
investments = investments.joins(:deal).where(user_id: u.id, deals: { funding_type_id: 3 })
that should generate following sql (subbing in 1
u.id
):
select "investments".* "investments" inner join "deals" on "deals"."id" = "investments"."deal_id" "investments"."id" = 1 , "deals"."funding_type_id" = 3
which should give rows want.
if set has_many :through
association (see association basics guide) between user
, deal
, can directly access deals belonging user:
# user.rb has_many :deals, through: :investments
you can deal particular user using:
user_deals = user.deals
you can optionally put where
condition on limit way want. u
user want deals for:
deals = u.deals.where(funding_type_id: 3)
Comments
Post a Comment