2013-12-14 44 views
0

檢索具有指定特徵集的所有獨特場所的最有效方法是什麼?從Rails 4關聯模型檢索信息

在控制器中,我有:

@venues = Venue.all 
@venues = @venues.features.where('feature.id == ' 1).distinct 

下面是我的模型定義:

class Neighborhood < ActiveRecord::Base 
    has_many :venues 
end 

class Venue < ActiveRecord::Base 
    belongs_to :neighborhood 
    has_many :features 
end 

class FeatureType < ActiveRecord::Base 
    has_many :features 
end 

class Feature < ActiveRecord::Base 
    belongs_to :venue 
    belongs_to :feature_type 
end 

回答

2

Ju st用英語思考這個問題。如果場館有許多功能,並且您問「功能的標識是什麼?」答案將是:「有很多功能,哪一個?」

:has_many關聯爲您提供以下方法:venure.features。這給你所有的「許多」相關功能。要獲得只有一個的ID,您可以執行如下操作:venue.features.first.id

+0

好點,Messick;不過,我確實在循環中有代碼(請參閱編輯的問題以獲取更多代碼)。出於某種原因,鐵軌不會選擇「id」字段。思考? – Vee

+0

我編輯了這個問題放回原來的文本,所以我們的答案是有道理的。 – messick

1

地點has_many功能,所以你必須遍歷集合,Vs的belongs_to哪裏有模型之間的單一關係

<% venue.features.each do |feature| %> 
    <%= debug feature %> 
<% end %> 
+0

感謝您指出調試方法house9。實際上我的代碼有一個循環(請參閱編輯的問題)。無論如何,我得到的錯誤是rails無法識別「id」字段。思考? – Vee

+0

當你寫sql片段時,你需要複用表名 - features.id – house9