试图分而治之这些问题(1、2 )我仍然有。我想在我的嵌套多对多模型中从虚拟属性编写 BLT 配方的第一步。后来我想要一个更复杂的形式,因此我在模型中这样做。
除了配方名称外,我已经对模型中的所有内容进行了硬编码。这是配方模型:
class Recipe < ActiveRecord::Base
has_many :steps, :class_name => 'Step'
has_many :stepingreds, :through => :steps
has_many :ingredients, :through => :stepingreds
accepts_nested_attributes_for :steps, :stepingreds, :ingredients
attr_writer :name_string
after_save :assign_name
def name_string
self[:name]
end
def assign_name
if @name_string
self[:name] = @name_string
self[:description] = "Addictive sandwich"
self.steps = Step.create({
:number => 1,
:instructions => 'Cook bacon',
:stepingreds => [{ :ingredient => { :name => 'Bacon' }, :amount => 4 } ]
})
end
end
这是表格
<%= form_for @recipe do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name_string, "Name" %><br/>
<%= f.text_field :name_string %>
</p>
<p><%= f.submit %></p>
<% end %>
我收到“RecipesController#create 中的 NameError,未定义的局部变量或方法 `attribute' for #”。我想我有不止一个错误,但这似乎对我有用。我究竟做错了什么?
谢谢!
编辑 - 这是 RecipeController 创建操作
def create
@recipe = Recipe.new(params[:recipe])
if @recipe.save
redirect_to @recipe, :notice => "Delicious BLT created!"
else
render :action => 'new'
end
end