2010-12-03 12 views
1

通知liked_image_user/loved_image_userの継承モデル

self.image 
self.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.likedまたはuser.images.lovedで任意のユーザーの画像を追加しました。

2つの評価を文字列に結合し、評価タイプのスコープを作成した場合、これはよりクリーンになる可能性があります。アプリケーションがどのように正確に動作するかによって異なります。

関連する問題