国家/地区名称未保存到表格或在视图轨道中显示3

时间:2012-11-11 10:13:48

标签: ruby-on-rails-3 activerecord

我有一个简单的应用程序,您可以上传食谱

我刚刚整合了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 个答案:

答案 0 :(得分:1)

在这段代码中,我看到两个错误:

  1. Recipebelong_to :country。请勿在此处使用has_one。外键country_id应位于recipes表中。
  2. @recipe.build_country没有必要。您已有国家/地区列表。如果您计划将新国家/地区添加到国家/地区列表中,则只应使用build_country
  3. 此外,您不需要fields_for。你可以这样做:

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