Ruby on Rails的HAS_MANY:通过协会,与同型号的两列 [英] ruby on rails has_many :through association which has two columns with same model

查看:113
本文介绍了Ruby on Rails的HAS_MANY:通过协会,与同型号的两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

class UserShareTag < ActiveRecord::Base
  attr_protected :sharee_id, :post_id, :sharer_id

  belongs_to :sharer, :class_name => "User"
  belongs_to :post
  belongs_to :sharee, :class_name => "User"

  validates :sharer_id, :presence => true
  validates :sharee_id, :presence => true
  validates :post_id, :presence => true
end

在Post模型,我有以下行:

In the Post model, I have the following line:

has_many :user_share_tags, :dependent => :destroy
has_many :user_sharers, :through => :user_share_tags, :uniq => true, :class_name => "User"
has_many :user_sharees, :through => :user_share_tags, :uniq => true, :class_name => "User"

我如何传达:user_sharers应符合下列条件:sharer_id?和:user_sharees应该对应于:sharee_id?由于它们两者是相同的用户模型,我不知该怎么办。

How do I convey that :user_sharers should correspond to :sharer_id? and :user_sharees should correspond to :sharee_id? Since they both are the same User model, I am unsure what to do.

有些相关的问题 - 在用户模式,我有:

Somewhat related problem - in the User model I have:

has_many :user_share_tags, :dependent => :destroy
has_many :user_shared_posts, :through => :user_share_tags, :uniq => true, :class_name => "Post"
has_many :recommended_posts, :through => :user_share_tags, :uniq => true, :class_name => "Post"

我如何合并的附加逻辑:user_shared_posts应该包含的职位,其中:sharer_id是USER_ID?和:recommended_posts应该包含的职位,其中:sharee_id是USER_ID

How do I incorporate the additional logic that :user_shared_posts should contain the posts where the :sharer_id is the user_id? and :recommended_posts should contain the posts where the :sharee_id is the user_id?

在此先感谢!

推荐答案

您只需要一个补充:源参数到你的的has_many 协会(你不需要:CLASS_NAME 选项):

You just need to add a :source parameter to your has_many associations (and you don't need the :class_name option):

has_many :user_sharers, :through => :user_share_tags, :source => :sharer, :uniq => true, :class_name => "User"
has_many :user_sharers, :through => :user_share_tags, :source => :sharee, :uniq => true, :class_name => "User"

然后在你的用户模型,需要一个额外的的has_many 关联:

Then in your User model, you need an extra has_many association:

has_many :user_share_tags_as_sharee, :class_name => "UserShareTag", :foreign_key => :sharee_id, :dependent => :destroy
has_many :user_share_tags_as_sharer, :class_name => "UserShareTag", :foreign_key => :sharer_id, :dependent => :destroy
has_many :user_shared_posts, :source => :post, :through => :user_share_tags_as_sharer, :uniq => true
has_many :recommended_posts, :source => :post, :through => :user_share_tags_as_sharee, :uniq => true

这篇关于Ruby on Rails的HAS_MANY:通过协会,与同型号的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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