2011-09-13 113 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

您有三種可能的解決方案。 (我喜歡的第三方法)

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

好的,謝謝,我結束了使用類似第三種選擇的東西。我只是返回一個「有」錯誤的實例。 – Tim

+0

這是''實例'方法而不是'靜態'方法的好候選。 –