我有一个Subject模型,它代表一个带有父子节点的树视图。
要将主题移动到另一个分支/节点,我需要有一个2个主题id代表from和to values。
我已经开始将所有逻辑放入控制器,但我现在想要重用复制方法并希望在模型中进行设置。
以下是我的一些控制器代码。
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
我首先关心的是如何在模型中的静态方法中添加错误?
我不确定我是否通过使用静态方法或实例方法以正确的方式进行操作。
任何人都能在重构此代码方面给我一些帮助吗?
答案 0 :(得分:1)
您有三种可能的解决方案。 (我更喜欢第三种方法)
1)成功时返回nil,失败时返回错误字符串
# 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