nested_form存在问题,模型关联深层次

时间:2012-02-21 17:22:27

标签: ruby-on-rails ruby associations nested-forms

我在创建嵌套表单时遇到问题,该表单可以使用nested_formsimple_form插件与以下域模型一起正常运行。我认为我正在构造错误的表单或attr_accessible和accepts_nested_attributes_for调用。

我有这个域模型,其中包含以下关联:

company.rb

class Company < ActiveRecord::Base 
  has_one :subscription

  attr_accessible :name, :subscription_attributes, :cycles_attributes, :payments_attributes
  accepts_nested_attributes_for :subscription
end

subscription.rb

class Subscription < ActiveRecord::Base
    belongs_to: company
    has_many :cycles

    attr_accessible :company_id, :cycles_attributes, :payments_attributes
    accepts_nested_attributes_for :cycles
end

cycle.rb

class Cycle < ActiveRecord::Base
    belongs_to :subscription
    has_many :payments

    attr_accessible :payments_attributes
    accepts_nested_attributes_for :payments
end

payment.rb

class Payment < ActiveRecord::Base

  belongs_to :cycle

end

我的观点如下:

<%= simple_nested_form_for company do |f| -%>
  <%= f.input :name %>

  <%= f.fields_for :subscription do |s| %>
  #assorted fields for subscription

    <%= s.fields_for :cycles do |c| %>
      #assorted fields for cycle
      <%= c.link_to_remove "[ - ] Erase Cycle"  %>

      <%= c.fields_for :payments do |p| %>
        #assorted fields for payments
        <%= p.link_to_remove "[ - ] Erase Payment"  %>
      <% end %>

      <%= c.link_to_add "[ + ] New Payment", :payments %>

    <% end %>
  <%=  s.link_to_add "[ + ] New Cycle", :cycles %>

<% end %>

公司控制人员:

def new
  @company = Company.new
  @company.build_subscription

  @categories = Category.find(:all)

  respond_with @company
end

def create
  @company = Company.new(params[:company])

  if @company.save 
    flash[:notice] = "Success"
  else
    flash[:error] = "Error #{@company.errors.full_messages}"
  end

  respond_with @company
end

当然,我正在简化视图和内容,有一些我没有展示的验证和字段,但这些都不是问题。 当我提交表单时,我遇到了一些奇怪的错误,基本上所有信息都在params中传递但是它没有正确嵌套:/

Parameters: {"utf8"=>"✓", "authenticity_token"=>"57wgXJinL6kql0F9CxShKpf11RhdMfqXnb6y8K/pDg0=", 
"company"=>{"name"=>"asdf12",
  "subscription_attributes"=>{
    "cycles_attributes"=>{
      "0"=>{"plan_id"=>"1", "amount"=>"123", "months"=>"12", "_destroy"=>"false"}
    }, 
    "0"=>{
      "0"=>{
        "payments_attributes"=>{
          "new_1329843584974"=>{"payment_type"=>"Efectivo", "amount"=>"123", "receipt_number"=>"1231", "note"=>"asdf asdf", "_destroy"=>"false"
           }
        }
      }
    }
  }
}, "commit"=>"Save"}

WARNING: Can't mass-assign protected attributes: 0

错误是:

@messages={:"subscription.cycles.subscription"=>["can't be blank"],
           :"subscription.cycles.payments"=>["can't be blank"]}

关于如何将属性传递给应用程序会出现问题,我的猜测是,当我点击新的付款按钮时,它会在表单“外部”创建...有没有人遇到类似的东西?< / p>

如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

问题在于nested_form插件本身。

当拥有has_one关系和嵌套模型作为子项时,nested_form在生成表单时遇到问题。

我查看了这个拉取请求,并使用更改

修补了相应的文件

Issue #124 in the nested_form repo

the patch that fixes the issue

此代码最终应合并到主仓库中。