Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord,double属于_Ruby On Rails_Activerecord_Model - Fatal编程技术网

Ruby on rails ActiveRecord,double属于

Ruby on rails ActiveRecord,double属于,ruby-on-rails,activerecord,model,Ruby On Rails,Activerecord,Model,我有两种型号:Link和User,例如: class Link < ActiveRecord::Base belongs_to :src_user belongs_to :dst_user end class User < ActiveRecord::Base has_many :links end 我的问题是:如何编辑Usermodel do才能做到这一点 (…应查询@user.src_users+@users.dst_users,如果可能,使用unicity。)

我有两种型号:
Link
User
,例如:

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

class User < ActiveRecord::Base
  has_many :links
end
我的问题是:如何编辑
User
model do才能做到这一点

(…应查询@user.src_users+@users.dst_users,如果可能,使用unicity。)

我们只能在ActiveRecord中使用SQL来实现这一点吗? 非常感谢


(注意:我使用的是Rails 3.1.1)

这听起来非常类似于儿童/母亲/父亲问题,它有一个解决方案。也就是说,一个类型
的对象属于同一类型的多个对象(不一定与子对象的类型相同,但它所属的对象本身是同一类型)的问题

此解决方案非常陈旧,可能无法与Rails3中的最新样式方案同步,但它应该可以正常工作,或者只需很少修改。

您必须在用户模型内指定多个关系,以便它知道将附加到哪个特定关联

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链接
必须指定:class_name选项,因为关联名称不仅仅是:links。您可能还需要在链接模型中指定:inverse_of选项,但我不能确定这一点。不过,如果你这么做了也不会有什么坏处

要执行@user.links呼叫,您必须执行以下操作:

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

…因为ActiveRecord不提供将同一模型上的两个关联合并为一个关联的方法。

这不是默认行为吗?
链接
关联在用户中,它将在
链接
表中查询具有匹配用户id值的所有链接。
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 User < ActiveRecord::Base
  def links
    Link.where(['src_user = ? OR dst_user = ?', self.id, self.id])
  end
end