【发布时间】:2012-12-13 18:41:43
【问题描述】:
我希望更好地了解活动模型/记录关系以及如何根据属性所在的位置(模型)以及我调用它们的位置来调用属性。因此,例如,我可以像这样从配方控制器中访问属性 disc_name
def all_recipes
@recipes = Recipe.all
end
在视图中
<% @recipes.each do |r| %>
<%= r.dish_name %>
<% end %>
现在假设我想从我的控制器中访问一个名为 worldrecipes 的食谱属性,并且我刚刚编写了一个返回同一国家/地区的所有食谱的方法。一个国家有许多食谱作为关系
所以我的方法是
def self.top_countries
joins(:recipes).
select('countries.*, count(*) AS recipes_count').
group('countries.id').
order('recipes_count DESC')
end
我的控制器
@worldrecipes = Country.where(:name => params[:name])
并查看
<% @worldrecipes.each do |r| %>
<%= r.name %>
<% end %>
所以访问国家名称属性很容易,因为它在国家模型中,这就是我的查询结果从(我认为)返回的地方......我的问题是我如何从我的食谱模型访问dish_name 属性国家名称的链接
希望这是有道理的,有没有人有关于如何解决这个问题的指南或一些黄金法则
谢谢
【问题讨论】:
-
是
@worldrecipes = Country.where(:name => params[:name])' give you the country record with name asparams[:name]` 还是那个国家的食谱数组?? -
它给了我记录名称为 params[:name] 因为在我看来我在页面上打印了“Italy”这个词,这并不完全正确,因为意大利有 2 条记录,只有 1 条正在显示
标签: ruby-on-rails-3 activerecord activemodel