如何在一定时期内检索深层关联的值?

时间:2014-03-14 07:32:19

标签: ruby-on-rails ruby

我有以下型号:

Company has_many :businesses

Business belongs_to :company
Business has_many :employees

Employee belongs_to :business
Employee has_many :votes

Vote belongs_to :employee
attr_accessible :score

从公司获得所有投票的所有投票的最佳方式是什么?属于该公司所有业务的所有员工?

我会使用has_many或创建查询还是使用gem?

然后我如何将结果限制为仅显示过去30天/ 1个月前的分数?

我试过了:

scores = self.businesses.employees.votes.where(created_at: Date.today.1.month.ago).pluck(:score)

我也试过了     公司has_many:企业     公司has_many:投票,通过:: business

Business belongs_to :company
Business has_many :employees
Business has_many :votes, through: :employees

Employee belongs_to :business
Employee has_many :votes

Vote belongs_to :employee
attr_accessible :score

@company.votes.pluck(:score)

我正在使用postgresql

1 个答案:

答案 0 :(得分:0)

这样的事情:

Vote.joins(:employee => :business).where('businesses.company_id = ?', id)

获取属于当前公司(id)的企业员工的所有投票。

编辑:

回答你的后续问题:

Vote.joins(:employee => :business).where('businesses.company_id = ?', id).where('votes.created_at > ?', Date.today - 1.month)