【发布时间】:2014-06-30 01:52:40
【问题描述】:
我有 5 个模型,我需要创建一个可以为每个模型创建一个新对象的唯一表单。模型是
Contract.rb
belongs_to :establishment
Establishment.rb
has_many :contracts
belongs_to :address
belongs_to :client
Address.rb
has_many :establishments
belongs_to :zip
Client.rb
has_many :establishments
Zip.rb
has_many :addresses
将创建对象的表单是Contract的表单
我的第一种方法是为其他模型创建 fields_for each,例如:
_form.html.erb
<%= form_for(@contract) do |f| %>
<% if @contract.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@contract.errors.count, "error") %> prohibited this contract from being saved:</h2>
...#fields for contract
<%= f.fields_for @client do |client|%>
<%=client.label 'Name'%><%=client.text_field :name%>
...#other fields for client
<%= f.fields_for @address do |address|%>
<%=address.label 'Street'%><%=address.text_field :street%>
...#other fields for address
<%=f.fields_for @zip do |zip|%>
<%=zip.label 'Code'%><%=zip.number_field :code%>
...#other fields for zip
表单运行良好,并且正在获取所有字段,但在ContractController.rb 上,我无法访问参数上的地址、客户和邮编字段。如果我使用@client = Client.create(params[:client]),它不会出错,但不会在模型上创建对象。我意识到params[:client](以及其他不用于合同的参数是 NIL)。然后我使用了params[:contract][:client],我得到了错误ForbiddenAttributesError...
所以,我决定改变方法并开始考虑多级嵌套属性,但我仍然没有得到......
我已将模型更改为:
Contract.rb
belongs_to :establishment
accepts_nested_attributes_for :establishment
has_one :address, through: :establishment
accepts_nested_attributes_for :address
has_one :zip, through: :address
accepts_nested_attributes_for :zip
has_one :client, :through => :establishment
accepts_nested_attributes_for :client
在控制器上我已经完成了
ContractController.rb
def new
@contract = Contract.new
@establishment = @contract.build_establishment
@address = @establishment.build_address
@zip = @address.build_zip
@client = @establishment.build_client
end
但现在表单没有Client, Address and Zip 的字段
是否可以创建这种类型的表单?
【问题讨论】:
-
尝试将
fields_for @client更改为fields_for :client
标签: ruby-on-rails forms nested