在虚拟属性中写入嵌套模型的正确Ruby on Rails语法是什么



我仍在努力解决这些问题(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'"。我想我有不止一个错误,但这似乎对我来说应该有效。我做错了什么?

谢谢!

编辑-这是RecipeController创建动作

   def create
       @recipe = Recipe.new(params[:recipe])
       if @recipe.save
         redirect_to @recipe, :notice => "Delicious BLT created!"
       else
         render :action => 'new'
       end
     end                

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

self.steps = Step.create(...

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

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

https://github.com/pixeltrix/cookbook

最新更新