[英]Retrieving information from Rails 4 associated models
What is the most efficient way for retrieving all unique venues with a specified set of features? 检索具有指定功能的所有唯一场所的最有效方法是什么?
In the controller, I have: 在控制器中,我有:
@venues = Venue.all
@venues = @venues.features.where('feature.id == ' 1).distinct
Here's how my models are defined: 这是我的模型的定义方式:
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
Just think about this using English. 只是用英语考虑一下。 If a Venue has many Features and you ask "What is the Id of the Feature?" 如果场所具有许多功能,并且您问“功能的ID是什么?” the response is going to be: "There are many Features, which one?" 响应将是:“功能很多,哪一个?”
The :has_many
association gives you the following method: venure.features
. :has_many
关联为您提供以下方法: venure.features
。 That gives you all the of the "many" associated features. 这为您提供了所有“许多”相关功能。 To get the Id of just one, you could do something like: venue.features.first.id
. 要获得一个ID,您可以执行以下操作: venue.features.first.id
。
Venue has_many
features, so you must loop over the collection, vs a belongs_to
where there is a single relationship between the models 场地具有has_many
功能,因此您必须遍历集合,而不是模型之间存在单一关系的belongs_to
<% venue.features.each do |feature| %>
<%= debug feature %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.