2016-11-21 60 views
0

喜有3種型號:關鍵字,網站,導致Rails 3的模型聯接限制到一個結果

class Keyword < ActiveRecord::Base 
    has_many :results 
    has_many :sites, through: :results 
end 

class Site < ActiveRecord::Base 
    has_many :results 
    has_many :keywords, through: :results 
end 

class Result < ActiveRecord::Base 
    belongs_to :site 
    belongs_to :keyword 
end 

在sites_controller我想顯示所有關鍵字的列表,該關鍵字的最新結果一起和現場。

這個連接給我關鍵字的所有結果,我怎麼能限制它只是每個關鍵字的最新結果?

@keywords = Keyword.joins(:results).where("results.site_id = ?", @site.id).includes(:results).order('keywords.created_at ASC').load 

回答

0

逆轉created_at秩序,加入1的限制應該解決您的問題:

Keyword.joins(:results).where("results.site_id = ?", @site.id).includes(:results).order("keywords.created_at DESC").limit(1) 
+0

我試圖限制結果爲1個而不是關鍵字或關鍵詞秩序 – Drewsdesign