2011-09-02 76 views
1

我有以下型號:映射的has_many和belongs_to的到活動記錄關係對象

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 

我想所有的c及其對應於給定aActiveRecord::Relation對象的形式

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

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。真的很感謝在這方面的幫助。

在此先感謝。

回答

0

你可以做到這一點與一個named_scope

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

編輯:

我已經重讀你的問題,我認爲我missunderstood你的第一次。所以總結你的模型看起來是這樣的:

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 

你想得到所有的C是與B相關的給定的A,對嗎?在這種情況下,您需要的是您的A型號中的has_many :cs, :through => :b。所以,你的模型應該是這樣的:

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

編輯2:

您可以添加有通過對模型中的許多人甚至如果你不能改變它的文件包括從模塊的代碼。你可以這樣說:

首先要初始化器(在配置/初始化)這樣的:

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 

它應該管用。

+0

不幸的是我無法改變,因爲這是在安裝到系統中的寶石定義的關聯。我正在考慮創建一個ActiveRecord :: Relation,而不是構建一個C數組。您怎麼看? – Ishu

+0

看看我編輯的答案,並告訴我它是否工作。 – cicloon

0

好吧,考慮一下,再讀一遍我認爲你正在尋找的是has_many:通過關聯。然後

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)

+0

如何計算cs在這裏?像我上面計算的? – Ishu

+0

是的。 但我認爲有一個「更容易」的方法...我會更新我的答案。 – LapinLove404

+0

奧普斯,沒有看到cicloon用has_many回答:通過關聯已經。 – LapinLove404