我需要在创建has_many表单之前在组合框中预先选择一个值,如下所示:
**注意,我不需要任何+或 - 按钮,只需一个预选值就可以生成has_many表单。
* Numerodeprestações是我想要调用has_many表单的组合。
因此,根据过去选择的数量,我想创建fields_for
has_many关联。
任何人都可以帮助我?
我的代码:
控制器:
def new
@account_payable = Account.new kind: AccountKind::PAYMENT
build_installments
end
def build_installments
params[:number_of_installments].to_i.times do
@account_payable.installments.new
end
# now I need to return to new.html.slim view, and refresh the installments fields. Because now I have a new number of installments selected.
end
_form.html.slim
= simple_form_for @account_payable, url: financings_accounts_payables_path do |f|
= f.error_notification
.form-groups
= f.association :account_value, collection: @account_values,
label_method: :account_element_name, value_method: :id
= f.input :accountable_id, collection: []
= f.input :accountable_type, as: :hidden,
input_html: {value: @accountable_type}
= f.input :description, as: :text
= f.input :number_of_installments, collection: []
hr
#items
= f.simple_fields_for :installments do |installment|
= render 'installment_fields', f: installment
.col-md-12
hr
.form-actions
= f.button :submit
= link_to_cancel financings_accounts_payables_path
br
答案 0 :(得分:1)
如果您不需要随表单数据提交的实际数字,您可以远程将其提交给您的控制器,然后让控制器使用适当数量的嵌套字段呈现表单。呈现表单的控制器操作将具有以下内容:
def index
n = params[:num_children]
n.times do
@parent_object.build_[child_objects]
其中[child_objects]是嵌套实体。
确保您的控制器响应javascript(顶部为respond_to :js
)。您应该index.js.erb
呈现您的表单,例如:
$(#my_form).html("<%=render 'my_form' %>")
另外,请确保在AccountsPayable
模型中有这一行:
accepts_nested_attributes_for :installments