5個accept_nested_attributes我有以下型號協會:滑軌從collection_select unpermited參數
class Receipt < ApplicationRecord
validates :name, presence: true
has_many :items, inverse_of: :receipt
accepts_nested_attributes_for :items
end
class Item < ApplicationRecord
validates :name, presence: true
belongs_to :receipt, inverse_of: :items
belongs_to :variant, inverse_of: :items
end
class Variant < ApplicationRecord
validates :name, presence: true
belongs_to :product, inverse_of: :variants
has_many :items, inverse_of: :variant
end
試圖用simple_form提交含有來自變種選擇這樣的項目一個新的收據:
<%= simple_form_for @receipt do |f| %>
<div class="form-inputs">
<%= f.input :name, label: 'Receipt Number', required: :true %>
</div>
<div class="form-inputs">
<%= f.simple_fields_for :items do |builder| %>
<%= builder.collection_select(:variant, Variant.all, :id, :name, {prompt: 'Choose a Variant'}) %>
<% end %>
</div>
<br />
<div class="form-actions">
<%= f.button :submit, 'Save Receipt', class:"btn btn-primary" %>
</div>
<% end %>
with controller actions:
def new
@receipt = Receipt.new
@receipt.items.build
end
def create
@receipt = Receipt.create(receipt_params)
puts receipt_params
if @receipt.valid?
redirect_to receipts_path
else
render :new, status: :unprocessable_entity
end
end
private
def receipt_params
params.require(:receipt).permit(:name, items_attributes: [:id, :name])
end
我可以選擇t來自變體(以不同的形式和動作創建),但是在提交既沒有收據也沒有物品被存儲之後。該終端讀取與未經許可的參數:
*處理由ReceiptsController#創建以HTML 參數:{ 「UTF8」=> 「✓」, 「authenticity_token」=> 「tugJchKiHNKwQ53E/LGCJacbrqV86ydLHolRuaB9ngZJ4gQrodOLqrxki2fAwgEfpBkbbAOy2GtfHRjsqjWYyQ ==」, 「收到」=> { 「name」=>「bhbh」,「items_attributes」=> {「0」=> {「variant」=>「2」}}},「commit」=>「Save Receipt」} 未經許可的參數:變體 在0.2ms)BEGIN (0.1毫秒)ROLLBACK 未經許可的參數:變體
渲染收據/ new.html.erb內佈局/應用lication 變負荷(0.4ms)選擇 「變種」 * FROM 「變種」 渲染收據/佈局內new.html.erb /應用(18.2ms) 在473ms(查看已完成422無法處理的實體:465.0ms | ActiveRecord的:爲0.8ms)*
此外,您需要白名單'variant_id' – Pavan
@Pavan - 感謝您的信息。我忘了將它添加到允許的參數中。 更新了答案。 感謝隊友:) –
仍然無法正常工作。 ... 「receipt」=> {「name」=>「q1w2e3」,「items_attributes」=> {「0」=> {「variant_ id」=>「2」}}},「commit」=>保存收據「} (0.2ms)BEGIN 變量加載(1.8ms)SELECT」variants「。* FROM」variants「WHERE」variants「。」id「= $ 1 LIMIT $ 2 [[」id「,2],[ LIMERS「,1]] (0.2ms)ROLLBACK # 在佈局/應用程序中呈現收據/ new.html.erb 變量加載(0.6ms)SELECT」variants「。* FROM」變體「 佈局/應用程序中的渲染收據/ new.html.erb(23.5ms) 已完成422無法處理的實體.... –