gpt4 book ai didi

ruby-on-rails - Rails 4 嵌套表单未在显示/编辑时加载值

转载 作者:行者123 更新时间:2023-12-04 08:46:53 25 4
gpt4 key购买 nike

我有一个带有嵌套产品表单的订单表单。产品正确保存到数据库,但显示/编辑产品值未加载 - 字段显示但未填充。

订货型号:

has_many :products, dependent: :destroy
accepts_nested_attributes_for :products

产品型号:
belongs_to :order

订单 Controller :
before_action :set_order, only: [:show, :edit]

def new
@order = Order.new
@order.products.build
end

def show
# empty
end

def edit
# empty
end

def order_params
params.require(:order).permit(
:number,
:price,
products_attributes: [
:id,
:type,
:color
])
end

def set_order
if params[:id].present? && user_signed_in?
@order = Order.find(params[:id])
elsif params[:number].present? && params[:email].present?
@order = Order.find_by(number: params[:number], email: params[:email])
else
redirect_to welcome_index_path, alert: I18n.t('views.welcome.index.no_order_found')
end
end

路线.rb:
resources :orders do
get 'express', on: :new
end
post 'orders/status', to: 'orders#show'

_form.html.erb(编辑和显示都使用):
<%= form_for @order do |f| %>
<%= f.text_field(:number) %>
# etc.
<%= f.fields_for :products do |g| %>
<%= g.text_field(:color) %>
# etc.
<% end %>
<% end %>

最佳答案

你的代码看起来不错,它应该可以工作。您能否尝试以下更改以通过 @products在表单域中

<%= f.fields_for :products, @products do |g| %>
<%= g.text_field(:color) %>
# etc.
<% end %>

只需制作 @products变量在 new 中可用和 edit行动。喜欢以下
def new
#your code goes here ...
@products = @order.products.build
end


def edit
#your code goes here ...
@products = @order.products
end

关于ruby-on-rails - Rails 4 嵌套表单未在显示/编辑时加载值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31779089/

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