模型/ participant_attachment.rb
class ParticipantAttachment < ActiveRecord::Base
belongs_to :participant
has_many :shared_attachments
validates_presence_of :attachment
accepts_nested_attributes_for :shared_attachments, reject_if: :all_blank,
allow_destroy: true
end
模型/ shared_attachment.rb
class SharedAttachment < ActiveRecord::Base
belongs_to :participant
belongs_to :participant_attachment
end
shared_attachment.html.haml
%ul
- @participants.each do |participant|
= hidden_field_tag 'participant_attachments[shared_attachments_attributes][][participant_attachment_id]', @attachment.id rescue nil
%li
%label= participant.full_name
= check_box_tag "participant_attachments[shared_attachments_attributes][][participant_id]", participant.id, @shared_participants.include?(participant.id.to_s)
participant_attachments_controller.rb
def create_shared_participants
shared_participants = SharedAttachment.new(activity_params)
shared_participants.save
end
def activity_params
params.require(:participant_attachments).permit(
:participant_id, :attachment, shared_attachments_attributes: [:participant_id, :participant_attachment_id]
)
end
我正在尝试保存多个复选框&#39;使用accespts_nested_attributes_for的值。但得到像未知属性的错误:shared_attachments_attributes.any解决方案?
这是日志:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"efwsP0tQksCSQqwqoH2qJwANJ/OFChQviG+4Kz8SYgI=", "participant_attachments"=>{"shared_attachments_attributes"=>[{"participant_attachment_id"=>"14", "participant_id"=>"2"}, {"participant_attachment_id"=>"14", "participant_id"=>"4"}]}}
Completed 500 Internal Server Error in 15ms
ActiveRecord::UnknownAttributeError (unknown attribute: shared_attachments_attributes):
app/controllers/participant/participant_attachments_controller.rb:34:in `create_shared_participants'
提前致谢。
答案 0 :(得分:0)
问题很可能是由于fields_for
元素中未正确使用form_for
帮助程序造成的。
通常,当您在accepts_nested_attributes_for
中设置model
参数时,您会使用fields_for
将相关数据传递给控制器/模型,而不是手动设置它们你有:
#app/controllers/participant_attachments_controller.rb
Class ParticipantAttachmentsController < ApplicationController
def new
@participants = ParticipantAttachment.all
@participant_attachment = ParticipantAttachment.new
@participants.each do
@participant_attachment.shared_attachments.build
end
end
end
#app/views/participant_attachments/new.html.erb
<%= form_for @participant_attachments do |f| %>
<%= f.fields_for :shared_attachments do |sa| %>
<%= sa.text_field :participant_id %>
<%= sa.text_field :participant_attachment_id
<% end %>
<% end %>
这将自动为您提供3套&#34;嵌套&#34;模型属性,您可以将其发送到您的模型。
我不确定这是否可以直接解决您的问题,但我知道您应该做什么,以确保您能够获得您的应用程序正常工作