我希望更好地理解活动模型/记录关系以及如何根据属性所在的位置(模型)以及我调用它们的位置来调用属性.因此,例如,我可以从配方控制器中访问属性dish_name,如此 def all_recipes@recipes =
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属性到链接到国家的名字
希望这是有道理的,有没有人有关于如何解决这个问题的指导或一些黄金规则
谢谢
对于初学者,您需要确保在模型中设置关联:country.rb
class Country < ActiveRecord::Base has_many :recipes end
recipe.rb
class Recipe < ActiveRecord::Base belongs_to :country end
如果尚未执行此操作,请通过运行以下迁移将foreign_key属性添加到配方模型:
rails g migration add_country_id_to_recipe country_id:integer
现在您的关联已到位,您可以轻松查询各个国家/地区的食谱.在你的控制器中:
@worldrecipes = Country.where(:name => params[:name])
然后在你看来:
<% @worldrecipes.each do |c| %> <% c.recipes.each do |r| %> <%= r.dish_name %> <% end %> <% end %>
关于“黄金规则”,我强烈建议你查看Association Basics.这是一个概述你可以用协会做什么的地方.