【发布时间】:2012-02-21 17:22:26
【问题描述】:
我在使用nested_form 和simple_form 插件创建可以与以下域模型正常工作的嵌套表单时遇到问题。我认为我构造表单不正确或 attr_accessible 和 accept_nested_attributes_for 调用。
我有这个具有以下关联的域模型:
公司.rb
class Company < ActiveRecord::Base
has_one :subscription
attr_accessible :name, :subscription_attributes, :cycles_attributes, :payments_attributes
accepts_nested_attributes_for :subscription
end
订阅.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
循环.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
当然,我正在简化视图和内容,有一些验证和字段我没有显示,但这些都不是问题。 当我提交表单时,我遇到了一些奇怪的错误,基本上所有信息都在参数中传递,但没有正确嵌套:/
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"]}
属性传递给应用程序的方式出现了问题,我的猜测是,当我点击新的支付按钮时,它会在表单“外部”创建......有人遇到过类似的事情吗?
如果您需要更多信息,请告诉我。
【问题讨论】:
标签: ruby-on-rails ruby associations nested-forms