问题描述
我有两个模型合同
和附录
。合约 has_many:附录
和附录属于:contract
I have two models Contract
and Addendum
. Contract has_many :addendums
and Addendum belongs_to :contract
创建新合同时,将自动创建一个新的附录,但是需要一些附加的元素来创建新的附录。如何在合同的窗体上添加字段 value
,该字段是附录的属性,而不是合同的属性?
When a new Contract is created, automatically will create a new Addendum but some aditional elements are needed to create the new Addendum. How can I add a field value
, which is an attribute from Addendum but not from Contract, on the Contract's form?
推荐答案
您正在寻找的是嵌套表格,这在RoR中很常见。有关嵌套和复杂表单的更多信息,Rails指南的。我建议您查看所有,这些指南在学习框架时非常有用。
What you're looking for is a nested form, which is pretty common in RoR. For more information on nested and complex forms, there's a section of a Rails Guide for that. I'd recommend checking out all of the Rails Guides, which are incredibly helpful when learning the framework.
对于您的特定问题,首先将您的合同
模型告诉 accept_nested_attributes_for
您的附录
模型。
For your specific question, first tell your Contract
model to accept_nested_attributes_for
your Addendum
model.
class Contract < ActiveRecord::Base
has_many :addendum
accepts_nested_attributes_for :addendums
end
接下来,打开您的合同控制者,然后做两件事。一种,在制作新的合约
时建立附录
。第二,在 contract_params
方法中允许附录
(假设您使用的是rails 4)的嵌套属性。
Next, open up your contract controller, and do two things. One, build an addendum
when making a new contract
. Two, allow the nested attributes of addendums
(assuming you're using rails 4) in your contract_params
method.
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
最后,在合同中添加
的表单。 forms_for
助手
Last, add the forms_for
helper in your contract
s form.
<%= 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 %>
有了这一点,您应该已经准备就绪!祝您编程愉快!
With that, you should be all set! Happy coding!
这篇关于Ruby on Rails-在另一个模型的表单上添加模型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!