问题
I'm trying to set up a complex association where the User model is used two times. Once to create the leader of a discussion and then to create the participants for the discussion.
First, do I have the associations correct in order to call multiple participants (users) for a discussion led by one user (leader)?
User
has_many :discussions, foreign_key: :leader_id
belongs_to :received_discussions, class_name: 'Discussion'
attr_accessible :participant_id
Discussion
belongs_to :leader, class_name: 'User'
has_many :participants, class_name: 'User', foreign_key: :participant_id
And second, how would I build the action to assign multiple users as participants?
Form:
.offset2.span7.mtop20
= simple_form_for @discussion, html: { multipart: true } do |f|
%fieldset.well
.mtop10
= f.input :participant_ids, label: 'Send to: (select from members you follow)', as: :select, collection: participants_for_discussion, input_html: { class: 'followed-ids-select', multiple: true }
= f.input :title
= f.input :description
.form-actions
= f.submit 'Send', name: 'send_now', class: 'btn btn-primary btn-large pull-right mleft10'
= f.submit 'Save and View Draft', name: 'save_draft', class: 'btn btn-large pull-right'
discussion_controller
def create
#not sure how to assign the participants in the action
@discussion = current_user.discussions.build(params[:discussion])
if @discussion.save
redirect_to @discussion, notice: draft_or_sent_notice
else
render :new
end
end
The error I'm getting is Can't mass-assign protected attributes: participant_ids
回答1:
First of all you want to have has_and_belongs_to_many between User and Discussion, both when a user is a leader or participant.
First you should make the decision if you want to user habtm or has_many :through association http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many
Then remodel your associations and the rest of your problems should solve themselves.
来源:https://stackoverflow.com/questions/17622827/creating-multiple-participants-in-the-user-model