2010-12-21 5 views
0

私はこのためにRails 3を使用しています。私は、コレクションモデル、ユーザーモデル、および中間サブスクリプションモデルを持っています。このようにして、ユーザーは特定の役割を持つ複数のコレクションにサブスクライブすることができます。しかし、ユーザーが同じコレクションを2回購読できないようにしたい。デュアルカラムバリデーションの良い方法

だから私のサブスクリプションモデルでは、私が持っている何かは次のように:

validate :subscription_duplicates 

def subscription_duplicates 
    self.errors.add_to_base "This user is already subscribed" if Subscription.where(:user_id => self.user.id, :collection_id => self.collection.id) 
end 

は、しかし、これは醜いようです。私はビルドを行うと

def create 
    @collection = Collection.new(params[:collection]) 
    @collection.subscriptions.build(:user => current_user, :role => Subscription::ROLES['owner']) 
    @collection.save 
    respond_with(@collection) 
end 

は、サブスクリプションIDを持っていないので、私はエラー「ゼロを呼びかけID」を取得する:私は私のコレクションコントローラで、次のような何かをしたいときにも、それが壊れます。

ありがとうございました!

validates_uniqueness_of :user_id, :scope => :collection_id 

答えて

3

使用、あなたの作成アクションは常に、新しい/編集ページを再レンダリングすると、エラーを示すことによって、通常は(それを扱うオブジェクトが保存されたかどうかをテストし、そうでない場合必要がありますユーザーへ)。アクションを作成する

標準ソートは(この場合は@postのために)次のようになります。重複があなたのため正常に動作する必要があります回避へ

def create 
    @post = Post.new(params[:post]) 
    @created = @post.save 
    respond_to do |format| 
    if @created 
     flash[:notice] = 'Post was successfully created.' 
     format.html { redirect_to @post } 
     format.xml { render :xml => @post, :status => :created, :location => @post } 
     format.js 
    else 
     format.html { render :action => :new } #or edit or wherever you got here from 
     format.xml { render :xml => @post.errors, :status => :unprocessable_entity } 
     format.js 
    end 
    end 
end 

Shingaraのアプローチを。

0

まずvalidates_uniqueness_of