0

我正在关注一个railscast,试图创建一个添加链接来添加一个与多对多关联相关的值。我使用模型而不是实现多对多的唯一区别

has_and_belongs_to_many. 

而且效果不太好。
(presenetation 很好,但添加按钮失败。)

这是我的代码

文件:ingredient_recipe.rb

class IngredientRecipe < ActiveRecord::Base
  attr_accessible :created_at, :ingredient_id, :order, :recipe_id
  belongs_to :recipe
  belongs_to :ingredient
end

文件:ingredient.rb

class Ingredient < ActiveRecord::Base
 has_many :ingredient_recipes
 has_many :recipes, :through => :ingredient_recipes
 ...

文件:recipes.rb

class Recipe < ActiveRecord::Base
 has_many :ingredient_recipes
 has_many :ingredients, :through => :ingredient_recipes
 ...

在用户界面中

 <%= link_to_add_fields "Add", f, :ingredient_recipes %>

该方法已定义

def link_to_add_fields(name, f, association)
 new_object = f.object.class.reflect_on_association(association).klass.new
 fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
   render(association.to_s.singularize + "_fields", :f => builder)
 end
 link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end

问题

渲染(association.to_s.singularize + "
_fields", :f => builder)显示
<%= f.text_field :name%> <%= f.hidden_​​field :_destroy%> <%= link_to "x","" , class: "remove_fields"%> 并打印错误

 ActionView::Template::Error (undefined method `name' for #<IngredientRecipe:0x6393ee8>):

有任何想法吗?

4

1 回答 1

1

不完全确定是不是这样,但由于它试图在成分食谱对象上调用名称,您是否尝试过更改方法中传递的符号?

 <%= link_to_add_fields "Add", f, :ingredients %>
于 2012-06-09T15:43:40.087 回答