2011-07-29 29 views
0

有一個標準Rails的:包括一個方法

def mutual_friends(friend) 
    self.friends & friend.friends 
end 

試圖:include => :profile

可以這樣做?

如果不是,有人可以幫我一個這個範圍版本?

考慮到用戶有:

has_one :profile, :dependent => :destroy  
has_many :friendships, :dependent => :destroy 
has_many :friends, 
     :through => :friendships, 
     :conditions => "status = 'accepted'" 
+0

如果你想包括配置文件只是在你的模型中做這樣的事情:'default_scope includes(:profile)' – stephenmurdoch

回答

0

要回答你的問題有兩個方法可以做到這一點。 Rails的方式 1)創建一個模塊(在你的libs文件夾中)將共享方法添加到該模塊,並將模塊包含在需要的類中。

的OO方式 2)創建自ActiveRecord :: Base的下降基類,使其一個抽象類,以避免STI和共用方法添加到基類然後下降朋友和友誼從

選項1例 朋友模型

#You might need to require the friends module for Rails 3 
require 'friends' 
include Friends 
class Friend < ActiveRecord::Base 
#... 
end 

只是做剖面模型和任何其它類需要這個 朋友模塊文件CA相同在lib文件夾LLED friends.rb

module Friends 
    module ClassMethods 
     #put your class methods here e.g. 
     def self.some_class_method 
     end 
    end 

    #put you instance methods here e.g. 
    def another_method 
    end 

# extend host class with class methods when we're included 
    def self.included(host_class) 
     host_class.extend(ClassMethods) 
    end 

end 

選項2例 base_friends.rb在模型文件夾(如果你喜歡林達)

class BaseFriends < ActiveRecord::Base 
    self.abstract_class = true 
    #All you usual methods that you want to share in the usual model way here 
end 

朋友模型 再次 - 只是做相同的輪廓和需要此

class Friend < BaseFriends 
    #... 
end 

任何其他車型,我更喜歡選擇2 - 這是乾淨多了,你都在同一個地方的文件(模型文件夾),它這很直觀(你已經熟悉在模型層中工作)以及這是Ruby的全部內容(OO)。選項1更適合於當你想要多重繼承時Rails不允許有很好的理由。

這回答你的問題,但我認爲你的問題是錯誤的 你不會通過一種方法來做到這一點。沒有必要,也沒有意義。上面的任一方法都可以讓你分享常見的方法,朋友和友誼通常可以在同一張桌子上工作,因此無論如何都是同一類,只需將class_name和foreign_key聲明添加到has_many友誼和belongs_to朋友聲明中即可。

+0

這是否適合你? – jamesc