复杂has_many通过关联

这对我来说是一个脑筋急转弯,但希望对经验丰富的人有所了解。 无法整理出正确的关联。

我有三个模型:用户,收件人,讨论

现在,关联是这样设置的:

讨论

belongs_to :user has_many :recipients 

用户

 has_many :discussions, dependent: :destroy has_many :discussions, :through => :recipients 

接受者

 belongs_to :user, dependent: :destroy belongs_to :discussion, dependent: :destroy 

当我尝试在discuss_controller中使用此操作创建讨论时:

 def create @discussion = current_user.discussions.build(params[:discussion]) @discussion.sent = !!params[:send_now] if params[:subscribe_to_comments] CommentSubscriptionService.new.subscribe(@discussion, current_user) end if @discussion.save redirect_to @discussion, notice: draft_or_sent_notice else render :new end end 

我收到此错误:

 Could not find the association :recipients in model User 

我还没有创建保存收件人的操作。

希望你的回答有助于清除第一个问题的蜘蛛网,即协会,然后我将继续讨论下一个问题。 欢迎任何建议。

看起来错误是正确的; 您在User模型中缺少收件人关联。

您的用户模型需要了解收件人模型才能使用has_many :through

尝试将此添加到您的用户模型:

 has_many :recipients 

编辑:实际上,从您的问题来看,我并不完全确定您希望如何布置模型。 您还应该只在用户模型中调用has_many :discussions一次。

你的桌子是如何布置的? 你的意思是为用户做这个: has_many :recipients, :through => :discussions

编辑2:

好的,从您的评论中,我认为用户不需要拥有多个收件人。 因此,在基本级别上,只需删除第二行即可使您的用户模型如下所示:

 has_many :discussions, dependent: :destroy 

您可能还需要删除收件人模型中的belongs_to :user

另一个可能的解决方案是概述您的模型,如下所示:

 class Discussion has_many :participants has_many :users, :through => :participants def leaders users.where(:leader => true) # I think this should work: http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/ end end class Participant belongs_to :user belongs_to :discussion # This class can have attributes like leader, etc. end class User has_many :participants has_many :discussions, :through => :recipients def leader?(discussion) participants.find_by(:discussion_id => discussion.id).leader? # doesn't seem super elegant end 

使用此解决方案,所有用户都作为参与者保持在一起,而不是让一个领导者拥有多个收件人。 在实施了一些之后,我不确定结果如何:P我会继续发布它,但你应该自己做出明智的决定。

我不是专家; 这只是你如何布置模型的另一种选择。 如果您有任何疑问,请告诉我。 我希望这有帮助!