對模型類使用繼承是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.liked
或user.images.loved
。
如果將兩個評分結合到一個字符串列中並創建評分類型的作用域,這可能會更清晰;這取決於你的應用程序將如何工作。