需要帮助构建rails查询

时间:2021-11-11 19:22:49

I have three models that Im working with here: User, Deal, and Investment.

我有三种模特在这里工作:用户,交易和投资。

User has many deals User has many investments

用户有很多交易用户有很多投资

Deal belongs to user Deal has many investments

交易属于用户交易有很多投资

Investment belong to deal Investment belong to user

投资属于交易投资属于用户

I want to find all investments from a user where the deal.deal_type_id = 3 for that investment.

我想查找来自用户的所有投资,其中deal.deal_type_id = 3用于该投资。

3 个解决方案

#1


2  

If you have setup your associations, its pretty simple.

如果您已经设置了关联,那很简单。

  # user.id = 1
  User.find(1).deals.where(:deal_type_id => 3)      

#2


1  

If you use the squeel gem, then it's quite a bit more intuitive.

如果你使用squeel gem,那么它会更加直观。

Assuming you've already retrieved the user you want to find investments for:

假设您已经检索了要查找投资的用户:

user.investments.joins{ deals }.where { deal.deal_type_id == 3 }

#3


0  

Like @Stephen said but for Active Record:

就像@Stephen说的那样但是对于Active Record:

type = 3
user.investments.joins('deals').where('deals.deal_type_id == ?', type)

#1


2  

If you have setup your associations, its pretty simple.

如果您已经设置了关联,那很简单。

  # user.id = 1
  User.find(1).deals.where(:deal_type_id => 3)      

#2


1  

If you use the squeel gem, then it's quite a bit more intuitive.

如果你使用squeel gem,那么它会更加直观。

Assuming you've already retrieved the user you want to find investments for:

假设您已经检索了要查找投资的用户:

user.investments.joins{ deals }.where { deal.deal_type_id == 3 }

#3


0  

Like @Stephen said but for Active Record:

就像@Stephen说的那样但是对于Active Record:

type = 3
user.investments.joins('deals').where('deals.deal_type_id == ?', type)