2011-09-13 18 views
0

親子ノードを持つツリービューを表すSubjectモデルがあります。レールの静的モデル検証

サブジェクトを別のブランチ/ノードに移動するには、値との関係を表す2つのサブジェクトIDが必要です。

私はすべてのロジックをコントローラに入れて始めましたが、コピーメソッドを再利用したいので、モデルに設定します。

ここに私のコントローラコードの一部があります。ここで

def copy 
    from = Subject.find(params[:from]) 
    to = Subject.find(params[:to]) 

    if to.is_descendant_of? from 
     render :json => {:error => ["Can't move branch because the target is a descendant."]}.to_json, :status => :bad_request 
     return 
    end 

    if to.read_only? 
     render :json => {:error => ["Can't copy to this branch as it is read only." ]}.to_json, :status => :bad_request 
     return 
    end 

    if params[:subjects] == 'copy' 
     subject = Subject.create(:name => from.name, :description => from.description, :parent_id => to.id) 

     #recursively walk the tree 
     copy_tree(from, subject) 
    else 
     #move the tree 
     if !(from.read_only or to.read_only) 
     to.children << from 
     end 
    end 

end 

class Subject < ActiveRecord::Base 



    def self.copy(from, to, operations) 

     from = Subject.find(from) 
     to = Subject.find(to) 

     if to.is_descendant_of? from 
      #how do I add validation errors on this static method? 

     end 

    end 
end 

私は私のモデルで始めたものです私の最初の懸念は、モデルの静的メソッドにエラーを追加する方法ですか?

静的メソッドまたはインスタンスメソッドを使用して正しい方法を実行するかどうかはわかりません。

このコードをリファクタリングするのに役立つ人は誰ですか?

答えて

1

解決策は3つあります。成功した場合にはnil(私は3番目のアプローチを好む)

1)戻り、失敗

# model code 
def self.copy(from, to, operations) 
    if to.is_descendant_of? from 
    return "Can't move branch because the target is a descendant." 
    end 
end 

# controller code 
error = Subject.copy(params[:from], params[:to], ..) 
if (error) 
    return render(:json => {:error => [error]}, :status => :bad_request) 
end 

2上のエラー文字列)エラー

def self.copy(from, to, operations) 
    if to.is_descendant_of? from 
    throw "Can't move branch because the target is a descendant." 
    end 
end 

# controller code 
begin 
    Subject.copy(params[:from], params[:to], ..) 
rescue Exception => ex 
    return render(:json => {:error => [ex.to_s]}, :status => :bad_request) 
end 

3のスロー例外)Subjectのインスタンスメソッドを追加します。クラス。

def copy_from(from, operations) 
    if is_descendant_of? from 
    errors.add_to_base("Can't move branch because the target is a descendant.") 
    return false 
    end 

    return true #upon success 
end 

# controller code 
from = Subject.find(params[:from]) #resolve from and to 
to = Subject.find(params[:to]) 

if to.copy_from(from) 
    # success 
else 
    # errors 
    return render(:json => {:error => [to.errors]}, :status => :bad_request) 
end 
+0

ありがとう、私は3番目のオプションのようなものを使用して終了しました。私はエラーの有無にかかわらず 'to'のインスタンスを返します。 – Tim

+0

これは 'static'メソッドではなく' instance'メソッドの良い候補です。 –

関連する問題