我有两个模型 Contract
和 Addendum
。契约(Contract) has_many :addendums
和附录 belongs_to :contract
创建新契约(Contract)时,会自动创建一个新附录,但需要一些附加元素来创建新附录。如何在 Contract 的表单上添加字段 value
,它是 Addendum 而非 Contract 的属性?
最佳答案
您要查找的是嵌套形式,这在 RoR 中很常见。有关嵌套和复杂表单的更多信息,请访问 section of a Rails Guide for that .我建议查看所有 Rails Guides ,这在学习框架时非常有用。
对于您的具体问题,首先将您的 Contract
模型告诉 accept_nested_attributes_for
您的 Addendum
模型。
class Contract < ActiveRecord::Base
has_many :addendum
accepts_nested_attributes_for :addendums
end
接下来,打开你的合约 Controller ,然后做两件事。一、在制定新的contract
时,建立一个addendum
。二,在 contract_params
方法中允许 addendums
的嵌套属性(假设您使用的是 rails 4)。
class ContractController < ApplicationController
def new
@contract = Contract.new
@addendum = @contract.addendums.build
end
protected
def contract_params
params.require(:contact).permit(:field1, :field2, addendums_attributes: [:id, :value, :other_field])
end
end
最后,在 contract
的表单中添加 forms_for
助手。
<%= form_for @contract do |f| %>
<!-- contract fields -->
Addendums:
<ul>
<%= f.fields_for :addendums do |addendums_form| %>
<li>
<%= addendums_form.label :value %>
<%= addendums_form.text_field :value %>
<!-- Any other addendum attributes -->
</li>
<% end %>
</ul>
<% end %>
有了这个,你应该准备好了!编码愉快!
关于ruby-on-rails - Ruby on Rails - 在另一个模型的表单上添加模型的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24297096/