2010-12-03 79 views
1

我有2種同類機型:在軌繼承模式

liked_image_user 
loved_image_user 

我已經把常用的方法模塊Rating.rb中,我包括在每個類 方法是:

update_score 
notify 

通知正在訪問

self.image 
self.user 

的成員likes_image_user/loved_image_user

我有2個問題:

  • 那是正確的設計?這似乎 ,我認爲我做的一個醜陋的 副作用,考慮到評級爲 基類,但它實際上是 只有一個模塊
  • 我寫 rating_test.rb,現在,有 問題測試通知,因爲 self.image是指夾具和 不是類的成員,是 有一種方法,我可以忽略夾具 並覆蓋self.image?

回答

2

對模型類使用繼承是Rails如何執行STI,因此可能不會達到您的預期。

這可能會變得一團糟,因爲你的關係設置錯了。我認爲這對於has_many :through關係更合適。

class User < ActiveRecord::Base 
    has_many :ratings 
    has_many :images, :through => :ratings do 
    def liked 
     where(:ratings => { :like => true }) 
    end 

    def loved 
     where(:ratings => { :love => true }) 
    end 
    end 
end 

class Rating < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :image 
    attr_accessible :like, :love 
    validates_with RatingValidator 
end 

class Image < ActiveRecord::Base 
    has_many :ratings 
    has_many :users, :through => :ratings 
end 

class RatingValidator < ActiveModel::Validator 
    def validate(record) 
    record.errors[:base] << "only one rating per image is allowed" unless record[:like]^record[:love] 
    end 
end 

隨着一點點的驗證和幾個簡單的範圍,你可以得到的喜歡/愛任何用戶的圖像與user.images.likeduser.images.loved

如果將兩個評分結合到一個字符串列中並創建評分類型的作用域,這可能會更清晰;這取決於你的應用程序將如何工作。