繁体   English   中英

将has_many和belongs_to映射到活动记录关系对象

[英]Mapping has_many and belongs_to to Active record relation object

我有以下型号:

Model A < ActiveRecord::Base
  has_many :bs
end

Model B < ActiveRecord::Base
  belongs_to :c, , :polymorphic => true, :foreign_type => 'c_type', :foreign_key => 'c_id'
end

我想以ActiveRecord::Relation对象的形式获取与给定a对应的所有c s

所以基本上我想删除以下方法

a.bs.each do |b|
  cs << b.c
end

因为这将输出一个c数组,但我希望能够获得一个c集合,可以在该集合上运行像这样的作用域:

cs.scoped(:order => :updated_at).all(:limit => 5)

我想我缺少一些简单的概念,例如映射可能是:

a.bs.map(&:to_resource) 

或类似的东西。

我正在运行Rails 2.3.14。 真的很感谢这方面的帮助。

提前致谢。

您可以使用named_scope做到这一点

class C < ActiveRecord::Base
  named_scope :by_a, lambda { |a| {:conditions => { :a_id => a.id }}
end

编辑:

我已经重读了您的问题,我认为我是第一次误解了您。 因此,总结一下您的模型如下所示:

class A < ActiveRecord::Base
  has_many :bs
end

class B < ActiveRecord::Base
  belongs_to :a
  belongs_to :c
end

class C < ActiveRecord::Base
  has_many :bs
end

您想通过B获得与给定A相关的所有C,对吗? 在那种情况下,您需要的是A模型中的has_many :cs, :through => :b 因此,您的A模型如下所示:

class A < ActiveRecord::Base
  has_many :bs
  has_many :cs, :through => :b
end

编辑2:

即使您不能修改其文件(包括来自模块的代码),也可以向模型A添加很多。 您可以这样进行:

首先像这样创建一个初始化程序(在config / initializers中):

require File.dirname(__FILE__) + '/../../lib/your_module.rb'
A.send( :include, YourModule)

然后在lib文件夹中创建一个如下所示的模块:

module YourModule

  def self.included(recipient)
    recipient.extend(ClassMethods)
  end
  module ClassMethods
    has_many :cs, :through => :b
  end
end

它应该工作。

好的,考虑一下并再次阅读,我认为您正在寻找的是has_many:through关联。

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Model A < ActiveRecord::Base
has_many :bs
has_many :cs, :through => :bs
end

Model B < ActiveRecord::Base
belongs_to :a
belongs_to :c, , :polymorphic => true, :foreign_type => 'c_type', :foreign_key => 'c_id'
end

然后应该可以直接访问a.cs

旧答案:不确定您要做什么,但是cs.sort_by(&:updated_at)呢?)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM