2011-09-13 5 views
0

부모 자식 노드가있는 트리 뷰를 나타내는 제목 모델이 있습니다.레일 정적 모델 유효성 검사

다른 브랜치/노드로 대상을 이동하려면 값과 값을 표현하는 2 개의 대상 ID가 있어야합니다.

저는 모든 논리를 컨트롤러에 넣었지만 이제는 복사 방법을 다시 사용하고자하며 모델에서 설정하려고합니다.

여기 내 컨트롤러 코드 중 일부입니다. 내가

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 

나의 첫번째 관심사는 모델에 정적 메서드에 오류를 추가하는 방법을 내 모델 일을 시작 여기에서

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 

은?

정적 메서드 나 인스턴스 메서드를 사용하여 올바른 방법으로 가고 있는지 확실하지 않습니다.

이 코드를 리팩토링하는 데 도움이 될만한 사람이 있습니까?

답변

1

세 가지 가능한 솔루션이 있습니다. Subject에서 인스턴스 메서드를 추가) 성공

1) 반환 전무,

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 오류에 실패

# 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) 던져 예외에 대한 오류 문자열을 (내가 3 방식을 선호) 수업.

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' 메소드의 좋은 후보입니다. –