2014-03-14 62 views
0

我有以下型號:如何檢索特定時期內深度關聯的值?

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 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

+0

你如何存儲票? – zogby

+0

我存儲了一個分數。更新 – grabury

回答

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) 
+0

謝謝@murrekatt。我嘗試解決方案時遇到postgresql錯誤:created_at不明確。當我添加vote.created_at它給了我錯誤丟失FROM子句 – grabury

+0

您使用的是什麼ruby和rails版本? – murrekatt