国家名称不保存到桌子或显示轨道3



我有一个简单的应用程序,您可以在其中上传配方

我刚刚整合了Gem Terrarum,为我的国家模型提供了世界所有国家。我有一种关系,一个食谱has_one国家和一个国家属于食谱。我正在使用瑞安·贝茨(Ryan Bates)的嵌套表格,并且从我的成分模型和准备模型中获取信息毫无疑问。但是我无法让国家名称保存在表中或在视图中显示(尽管这是由于不保存到模型而引起的)

代码如下

形式

<%= f.label :country_id, "Country Of Origin" %>
<%= f.collection_select(:country_id, Country.all, :id, :name, :prompt => 'Please select country') %>

查看

<% @recipes.each do |r| %>
<tr>
<td><%= r.dish_name %></td>
<td><%= r.country.name %></td>
<td><%= r.difficulty %></td>
<td><%= r.preperation_time %></td>
<td><%= ingredient_names(r.ingredients) %></td>
<td><%= preperation_steps(r.preperations) %></td>
<td><%= image_tag r.avatar.url(:thumb)%></td>
</tr>

助手

def preperation_steps(preperations)
if preperations
  preperation_array = preperations.map {|pre| pre.prep_steps}
  preperation_array.join("n")
end
end
def country_name(country)
if country
  country_array = country.map {|c| c.country_name}
  country_array.join("n")
end
end
end

我将我的准备助手包括在内,所以我的country_name助手当然会镜像吗?还是我不需要为此施加助手?

食谱控制器

def new 
@recipes = current_user.recipes if current_user.recipes #show recipes if the user has any recipes
 @favourites = current_user.favourites
end

食谱模型

  belongs_to :user
  belongs_to :country
  has_many :ingredients 
  has_many :preperations
  has_many :favourites
  attr_accessible :dish_name, :difficulty, :preperation_time, :ingredients_attributes, :preperations_attributes, :country_id, :avatar:preperations_attributes, :country_id, :avatar
  has_attached_file :avatar, :styles => {  :medium => "300x300>", :thumb => "100x100>" } 
  accepts_nested_attributes_for :ingredients, :preperations
  scope :top_countries, order("country_of_origin DESC")

如果有人可以提供帮助,将不胜感激

谢谢

在此代码中,我看到了两个错误:

  1. Recipe应该belong_to :country。在这里不要使用has_one。外键country_id应该在recipes表中。
  2. @recipe.build_country不是必需的。您已经有一个国家清单。如果您打算将新国家添加到国家/地区,则只能使用build_country

另外,您不需要fields_for。您可以做:

<%= f.label :country_id, "Country Of Origin" %>
<%= f.collection_select(:country_id, Country.all, :id, :name, :prompt => 'Please select country') %>

最新更新