2012-05-04 10 views
0

게시물 has_many Comments 연관이 있습니다. 게시물의 부울 속성은 published입니다. post.published이 거짓 일 때 새로운 설명이 유효하지 않아야합니다. 이러한 종류의 유효성 검사를 수행하는 가장 좋은 방법은 무엇입니까?레일에서 사용자 정의 유효성 검사

나는이 방법으로 시도했지만 슬프게도 제대로 작동하지 않습니다. 아직 게시되지 않은 게시물에 대해 새로운 코멘트를 작성할 수 있습니다.

class Comment < ActiveRecord::Base 
    validates :post_id, presence: true, if: :post_is_published 

    ... 
    def post_is_publised 
    post && post.published 
    end 
end 

답변

1

은 흠 .. 난 당신이 코드에 구문 오류가 있다고 생각 ...이 시도 :

class Comment < ActiveRecord::Base 
    validates :post_id, :presence => true, :if => :post_is_published 

    def post_is_publised 
    post.try(:published) 
    end 
end 

를 질문 한 번 더 콘솔 출력을 읽고 확인한 후 :

class Comment < ActiveRecord::Base 
    validate :post_has_to_be_published 

    def post_has_to_be_published 
    unless post.try(:published) 
     self.errors.add(:base, "you can add comments only to published posts") 
    end 
    end 
end 

게시되지 않은 게시물에 댓글을 추가하는 것을 허용하지 않으려한다는 점을 이해했습니다. 위의 코드는이를 수행해야합니다.

+2

[Object # try] (http://api.rubyonrails.org/classes/Object.html#method-i-try)를보고 코드를 아주 작게 말릴 수 있습니다. – x1a4

+0

'post.try (: published)'를 제안하셨습니까? 그 사실을 알지 못했지만, 분명히 감사합니다. –

+1

ActiveSupport에는 문서화가 잘되어 있지 않더라도 [유용한 자료] (http://guides.rubyonrails.org/active_support_core_extensions.html)가 있습니다. – x1a4

관련 문제