gpt4 book ai didi

ruby-on-rails - 具有嵌套 fields_for 的表单,可保存到多条记录

转载 作者:行者123 更新时间:2023-12-01 09:18:54 30 4
gpt4 key购买 nike

我有三个模型,companiestransactionssubtransactions。每个都有下一个。我需要构建一个表单来保存到 transactionssubtransactions 的多个记录。

我正在为表单的最佳方法和保存到数据库的适当方法而苦苦挣扎。理想情况下,如果所有记录都通过验证,记录将立即保存。

我的简化形式:

<%= form_for(@transaction) do |f| %>
<div class="field" id="transaction_amount">
<%= f.label :total %><br>
<%= f.text_field :total %>
</div>

<% 1.upto(5) do |i| %>
<%= fields_for("subtransaction[#{i}]") do |s| %>
<div class="field" id="subtotal_amount">
<%= s.label :subtotal, "Subtotal #{i}" %><br>
<%= s.text_field :subtotal %>
</div>
<% end %>
<% end %>
<% end %>

我的交易 Controller :

def new
@transaction = company.transactions.build if logged_in?
end

def create
@transaction = company.transactions.build(transaction_params)

params[:subtransaction].each do |i|
# build and save
end

if @transaction.save ## @subtransaction.save
flash[:success] = "Success!"
redirect_to success_url
else
render :new
end
end

最佳答案

这样做的方法是通过各种模型传递嵌套属性:

#app/models/company.rb
class Company < ActiveRecord::Base
has_many :transactions
accepts_nested_attributes_for :transactions
end

#app/models/transaction.rb
class Transaction < ActiveRecord::Base
has_many :sub_transactions
accepts_nested_attributes_for :sub_transactions
end

这将使您能够使用以下内容:

#app/controllers/transactions_controller.rb
class TransactionsController < ApplicationController
def new
@transaction = company.transactions.new
5.times do
@transaction.sub_transactions.build
end
end

def create
@transaction = company.transactions.new transaction_params
@transaction.save
end

private

def transaction_params
params.require(:transaction).permit(sub_transactions_attributes: [:subtotal])
end
end

然后...

#app/views/transactions/new.html.erb
<%= form_for @transaction do |f| %>
<%= f.fields_for :sub_transactions do |s| %>
<%= s.text_field :subtotal %>
<% end %>
<%= f.submit %>
<% end %>

这将允许您通过主对象保存各种嵌套属性。这是正确的,conventional , 方法来做到这一点。

关于ruby-on-rails - 具有嵌套 fields_for 的表单,可保存到多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35108416/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com