模型/参与者访问。
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模型/共享攻击。
class SharedAttachment < ActiveRecord::Base
belongs_to :participant
belongs_to :participant_attachment
endshared_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我试图使用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'提前谢谢。
发布于 2014-08-01 10:20:18
fields_for
这个问题很可能是由于在您的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组“嵌套”模型属性,您可以将这些属性发送到模型中。
我不确定这是否能直接解决您的问题,但我知道您应该这样做,以确保您的应用程序能够正常工作
https://stackoverflow.com/questions/25075731
复制相似问题