0

试图分而治之这些问题(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                
4

2 回答 2

1

我认为一个问题是以下行:

self.steps = Step.create(...

Steps是通过你的 has_many 协会。所以 selft.steps 将包含一个零到多步骤的列表。您的任务=是为其提供单个项目,这将破坏它。您真正想要的(我认为)是将 self.steps 创建为一个项目的列表,而不是一个项目。=将分配更改为<<应该可以实现这一点。

于 2011-07-24T18:10:56.597 回答
0

这是一个简单的 Rails 应用程序,可以满足您的需要:

https://github.com/pixeltrix/cookbook

于 2011-07-25T19:47:54.640 回答