我有以下模特协会:
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 %>
控制器操作:
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
我可以在表单中为新项目选择变体(以不同的形式和操作创建)但在提交既不接收也不存储项目。终端读取未允许的参数:
* ReceiptsController处理#create as HTML 参数:{“utf8”=&gt;“✓”,“authenticity_token”=&gt;“tugJchKiHNKwQ53E / LGCJacbrqV86ydLHolRuaB9ngZJ4gQrodOLqrxki2fAwgEfpBkbbAOA2GtfHRjsqjWYyQ ==”,“收据”=&gt; {“name”=&gt;“bhbh”,“items_attributes”=&gt; {“0”=&gt; {“variant”=&gt;“2”}}},“commit”=&gt;“保存收据”} 未允许的参数:变体 (0.2ms)BEGIN (0.1ms)ROLLBACK 未允许的参数:variant
在布局/应用程序中渲染收据/ new.html.erb 变量负载(0.4ms)SELECT“variants”。* FROM“variants” 在布局/应用程序中呈现收据/ new.html.erb(18.2ms) 在473ms完成422个不可处理的实体(浏览次数:465.0ms | ActiveRecord:0.8ms)*
答案 0 :(得分:1)
尝试使用
<%= builder.collection_select(:variant_id, Variant.all, :id, :name, {prompt: 'Choose a Variant'}) %>
而不是
<%= builder.collection_select(:variant, Variant.all, :id, :name, {prompt: 'Choose a Variant'}) %>
请参阅,我使用variant_id
代替variant
另外,允许variant_id
def receipt_params
params.require(:receipt).permit(:name, items_attributes: [:id, :name, :variant_id])
end