ActiveRecord的,双belongs_to的 [英] ActiveRecord, double belongs_to

查看:137
本文介绍了ActiveRecord的,双belongs_to的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个型号:链接用户如:

class Link < ActiveRecord::Base
  belongs_to :src_user
  belongs_to :dst_user
end

class User < ActiveRecord::Base
  has_many :links
end

一个模式可能看起来像:

A schema could looking like:

+----------+     +------+
| Link     |     | User |
+----------+     |------+
| src_user |---->|      |
| dst_user |---->|      |
+----------+     +------+

我的问题是:我怎么能修改用户模型做才能做到这一点

My question is: how can I edit User model do in order to do this

@user.links # => [list of links]

(...这应该查询@ user.src_users + @ users.dst_users,具有唯一性如果可能的话。)

(...which should query @user.src_users + @users.dst_users, with unicity if possible.)

我们能做到这一点只使用SQL中的ActiveRecord? 非常感谢。

Can we do this only using SQL inside ActiveRecord? Many thanks.

(注意:我on Rails的3.1.1)

(note: I'm on Rails 3.1.1)

推荐答案

您必须指定用户模型中多关系,所以它知道哪些特定的关联,将附加到。

You have to specify multiple relations inside the user model so it knows which specific association it will attach to.

class Link < ActiveRecord::Base
  belongs_to :src_user, class_name: 'User'
  belongs_to :dst_user, class_name: 'User'
end

class User < ActiveRecord::Base
  has_many :src_links, class_name: 'Link', inverse_of: :src_user
  has_many :dst_links, class_name: 'Link', inverse_of: :dst_user
end

的:必须指定选项将class_name因为该协会的名称并不是简单:链接。您可能还需要指定:inverse_of在链接模式的选择,但我不能肯定这一点。如果你没有它不会伤害,但。

The :class_name option must be specified since the association name is not simply :links. You may also need to specify the :inverse_of option in the Link model, but I can't be sure of that. It wouldn't hurt if you did, though.

为了做你的@ user.links电话,你就必须做这样的事情:

In order to do your @user.links call, you'll have to do something like this:

class User < ActiveRecord::Base
  def links
    Link.where(['src_user = ? OR dst_user = ?', self.id, self.id])
  end
end

...因为ActiveRecord的不提供一种方式来合并在同一个模型两个关联为一个。

… since ActiveRecord doesn't provide a way to merge two associations on the same model into one.

这篇关于ActiveRecord的,双belongs_to的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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