0
我正在做的似乎是Ruby on Rails,食譜應用程序的常見學習應用程序。具體而言,將食譜和配料作爲has_many:through關係進行工作。通過查看一百多個示例和問題,我已經獲得了我的多對多關係設置和多模式表單的工作方式,但是我想添加一個附加字段並且無法使其工作。感覺就像我接近了解這些東西的工作原理。下面是簡單信息:如何添加has_many:通過細節到一個表單RoR
型號:
class Ingredient < ActiveRecord::Base
has_many :recipe_ingredients
has_many :recipes, :through => :recipe_ingredients
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, :through => :recipe_ingredients
accepts_nested_attributes_for :ingredients, :recipe_ingredients
def new_recipe_ingredient_attributes=(recipe_ingredient_attributes)
recipe_ingredient_attributes.each do |attributes|
recipe_ingredients.build(attributes)
end
end
def existing_recipe_ingredient_attributes=(recipe_ingredient_attributes)
recipe_ingredients.reject(&:new_record?).each do |recipe_ingredient|
attributes = recipe_ingredient_attributes[recipe_ingredient.id.to_s]
if attributes
recipe_ingredient.attributes = attributes
else
recipe_ingredient.delete(recipe_ingredient)
end
end
end
def save_recipe_ingredients
recipe_ingredients.each do |recipe_ingredient|
recipe_ingredient.save(false)
end
end
end
控制器:
def create
@recipe = Recipe.new(params[:recipe])
if @recipe.save
redirect_to :action => 'show', :id => @recipe
flash[:notice] = "Your record has been saved."
else
render :action => 'new'
end
end
def update
params[:recipe][:existing_recipe_ingredient_attributes] ||= {}
@recipe = Recipe.find(params[:id])
if @recipe.update_attributes(params[:recipe])
redirect_to :action => 'show', :id => @recipe
flash[:notice] = "Your changes have been saved."
else
render :action => 'edit'
end
end
查看:
對不起,我的代碼在牆上,希望這是有道理的。我不明白的是爲什麼「金額」文本字段不起作用。我嘗試了一百萬種不同的方式,但無法使其工作。在這種情況下,我得到的錯誤是「未定義的方法`金額'爲#」
我在這裏丟失了什麼關鍵連接?謝謝。
感謝您抽空看看,但似乎這樣讓事情變得更糟。我現在有一個編譯錯誤。編譯錯誤 /home/jchandler/rails-tests/recipes/app/views/recipes/_recipe_ingredient.html.erb:4:語法錯誤,意外')' ... cipe_ingredient do | ri_form | ).to_s); @ output_buffer.concat ... ^ /home/jchandler/rails-tests/recipes/app/views/recipes/_recipe_ingredient.html.erb:12:syntax error,unexpected kENSURE,expected')' /home/jchandler /rails-tests/recipes/app/views/recipes/_recipe_ingredient.html.erb:14:語法錯誤,意想不到的kEND,期待')' – SenorPuerco
以及'/ views/recipes/_recipe_ingredient.html.erb'的第4行是什麼。 – apneadiving
對不起,您提出的建議修改的線路。 <%= fields_for前綴,recipe_ingredient do | ri_form | %> – SenorPuerco