【问题标题】:What is the Correct Ruby on Rails Syntax to Write to a Nested Model within a Virtual Attribute?在虚拟属性中写入嵌套模型的正确 Ruby on Rails 语法是什么?
【发布时间】:2011-07-21 09:28:41
【问题描述】:

试图分而治之(12)我仍然有。我想从虚拟属性在我的嵌套多对多模型中编写 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                

【问题讨论】:

  • 你能复制粘贴RecipesController create 动作吗?

标签: ruby-on-rails activerecord nested-forms nested-attributes virtual-attribute


【解决方案1】:

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

self.steps = Step.create(...

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

【讨论】:

    【解决方案2】:

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

    https://github.com/pixeltrix/cookbook

    【讨论】:

      猜你喜欢
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多