通过关联复杂has_many [英] Complex has_many through association

查看:93
本文介绍了通过关联复杂has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我来说是个脑筋急转弯,但希望对经验丰富的人来说很清楚.在整理正确的关联时遇到麻烦.

This is a brain teaser for me, but hoping it's clear to someone more experienced. Having trouble sorting out the correct associations.

我有三种型号: 用户,收件人,讨论

I have three models: User, Recipient, Discussion

现在,关联是通过以下方式设置的:

Right now the associations are set up this way:

讨论

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

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

When I try to create a discussion with this action in the discussions_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

我尚未创建保存收件人的操作.

I have not yet created the action for saving recipients.

希望您的回答有助于清除有关第一个问题的蜘蛛网,即关联,然后继续进行下一个讨论.欢迎任何建议.

Hoping your answer will help clear the cobwebs for this first issue, which is the association, then I'll move on to the next. Any suggestions are welcome.

推荐答案

另一种可能的解决方案是像这样概述模型:

Another potential solution would be to outline your models like this:

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我会继续进行发布,但是您应该自己做出明智的决定.

With this solution, all of the users are kept together as participants in the discussion, rather than having one leader with multiple recipients. After implementing some of it though, I'm not sure how neat it turned out :P I'll go ahead and post it, but you should make the informed decision yourself.

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

I'm no expert; this is just another alternative to how you have your models laid out. Let me know if you have any questions. I hope this helps!

这篇关于通过关联复杂has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆