我有一个名为 Order 的多重关系表,它属于一个 Relai(以避免单数/复数并发症)、一个客户和一个组合。我使用下面提到的nested_attributes 相应地设置了我的订单模型。在添加客户部分之前,我想发送一封邮件,其中只包含@composition 和一个带有下拉列表的@relai。
class Order < ApplicationRecord
belongs_to :relai
belongs_to :composition
accepts_nested_attributes_for :relai
accepts_nested_attributes_for :composition
end
我将我的 OrdersController 设置为从我的参数中获取 :composition_id
def new
@order = Order.new
@composition = Composition.find(params[:composition_id])
@relais = Relai.all
end
def create
@florist = Florist.first
@composition = Composition.find(params[:composition_id])
#@relai = Relai.find(params[:relai_id]) # If I add this line it returns "Couldn't find Relai without an ID"
@order = Order.new(order_params)
if @order.save!
raise
OrderMailer.order_mail(@order).deliver
redirect_to thanks_purchase_path
else
render :new
end
end
private
def order_params
params.require(:order).permit(
florist_attributes: [:id],
relai_attributes: [:id, :name, :address],
composition_attributes: [:id, :name]
)
end
我的观点:
<%= form_with(model: @order, url: composition_orders_path(@composition), local: true) do |compo| %>
<%= compo.collection_select :relai, @relais, :id, :name %>
<%= compo.fields_for :composition do |fc| %>
<%= fc.collection_select :composition, @compositions, :id, :name %>
<% end %>
# Start Block that doesn't display the Relai.all
#<%#= compo.fields_for :relai do |fr| %>
#<%#= fr.label :relai, 'Ici la liste des relais :' %>
#<%#= fr.association :relai, collection: @relais %>
#<%#= fr.association :relai, @relais, :id, :name %>
#<%# end %>
# End Block
<%= compo.submit "MAIL", class: "app-form-button" %>
<% end %>
和路线:
resources :compositions, only: [:show, :index] do
resources :orders, only: [:show, :new, :create, :index]
end
我也试过:
“nested_attributes”似乎不起作用(我看不到我的 Relai 收藏。=> https://www.pluralsight.com/guides/ruby-on-rails-nested-attributes)
模型中的“可选:真”给我一个错误:
PG::NotNullViolation:错误:关系“订单”的“relai_id”列中的空值违反非空约束
有人能解释一下为什么我得到“验证失败:Relai 必须存在,Composition 必须存在”,而这些出现在我的参数中吗?
{"authenticity_token"=>"[FILTERED]", "order"=>{"relai"=>"2"}, "commit"=>"MAIL", "composition_id"=>"3"}
我在 Rails 6.1.4 上;红宝石 2.6.6