轨道静态模型验证

问题描述:

我有一个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)上成功返回零,在失败

# 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

这是''实例'方法而不是'静态'方法的好候选。 –