访问来自不同关联模型的属性rails 3

时间:2012-12-13 18:41:43

标签: ruby-on-rails-3 activerecord activemodel

我希望更好地理解活动模型/记录关系以及如何根据属性所在的位置(模型)以及我调用它们的位置来调用属性。因此,例如,我可以从配方控制器中访问属性dish_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属性到链接到国家/地区名称

希望这是有道理的,有没有人有关于如何解决这个问题的指南或者这个

的一些黄金法则

谢谢

2 个答案:

答案 0 :(得分:4)

我认为你需要的是:

@country=Country.where(:name=>params[:name]).first
@worldrecipes=@country.recipes

在视图中:

<% @worldrecipes.each do |r|  %>
  <%= r.dish_name %>
<% end %>

这将打印由params[:name]

提供的名称的国家食谱的菜肴名称

编辑: 好的,让我为你清楚这一点:)

您的模型关系已设置为每个国家/地区都有许多食谱。即一个国家有很多食谱。

所以你有,

has_many :recipes
在country.rb和

belongs_to :country
在recipe.rb中

现在,当您想要访问属于某个国家/地区的所有食谱时,您要拨打country_record.recipes(country_record是您需要的国家/地区记录的对象)。

当你打电话时,     Country.where(:名称=&GT; PARAMS [:名称]) 你实际得到的是表示COUNTRY本身的活动记录对象,而不是国家的食谱,这就是意大利印刷的原因。

希望这有助于你。

答案 1 :(得分:3)

对于初学者,您需要确保在模型中设置关联:

<强> 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。这是关于你可以用关联做什么的概述的首选。

相关问题