【问题标题】:Creating multiple participants in the User model在用户模型中创建多个参与者
【发布时间】:2013-07-12 19:41:38
【问题描述】:

我正在尝试建立一个复杂的关联,其中用户模型被使用了两次。一次创建讨论的领导者,然后创建讨论的参与者。

首先,为了召集多个参与者(用户)进行由一个用户(领导者)领导的讨论,我的关联是否正确?

用户

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'

讨论控制器

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

【问题讨论】:

标签: ruby-on-rails controller associations has-many


【解决方案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

然后重塑你的联想,剩下的问题应该自己解决。

【讨论】:

  • 嘿迈克尔,我已经读到我应该避开 HABTM,但关于 has_many,我开始以这种方式创建它:stackoverflow.com/questions/17621313/… 然后改变方向以达到上述解决方案。很难理解这一点,因此将不胜感激。谢谢
  • 你在哪里读到的?这取决于您必须建模的内容 - 如果一个关联有它自己的参数参数 habtm 可能会有用。如果你想避免它,还有has_many :through
  • 布赖恩,上面不是一个“解决方案”,因为它完全是错误的!一方面,您不能与belongs_to 建立多对多关系!
  • 感谢您指出这一点。对于这种关联的最佳实践似乎没有共识:stackoverflow.com/questions/15960573/…
  • 啊,我在上面写了愚蠢的东西。我的意思是,如果一个协会有任何自己的属性,应该选择has_many :through。我个人也认为这是一个更好的选择,因为它更灵活。
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
相关资源
最近更新 更多