我正在尝试建立一个复杂的关联,其中User模型使用了两次。一旦创建讨论的领导者,然后创建参与者进行讨论。
首先,我是否有正确的关联,以便召集多个参与者(用户)进行由一个用户(领导者)领导的讨论?
用户
has_many :discussions, foreign_key: :leader_id
belongs_to :received_discussions, class_name: 'Discussion'
attr_accessible :participant_id
讨论
belongs_to :leader, class_name: 'User'
has_many :participants, class_name: 'User', foreign_key: :participant_id
第二,我如何构建将多个用户分配为参与者的操作?
形式:
.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
我得到的错误是Can't mass-assign protected attributes: participant_ids
答案 0 :(得分:1)
首先,当用户是领导者或参与者时,您希望在用户和讨论之间拥有has_and_belongs_to_many。
首先,如果您想通过关联使用habtm或has_many,您应该做出决定 http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many
然后重塑你的联想,其余的问题应该自己解决。