2014-11-21 7 views
3

의 속성에 지정 유효성 검사 오류 메시지를 레일 :내가 유효성 검사 오류 메시지에 링크를 삽입 할 내 모델에서 다음 코드를 사용하여 사용하고 다른 모델

class Bar < ActiveRecord::Base 
    has_many :foos 
    validate :mode_matcher 

    def mode_matcher 
    self.foos.each do |f| 
     errors[:base] << mode_mismatch(foo) unless foo.mode == "http" 
    end 
    end 

    def mode_mismatch(f) 
    foo_path = Rails.application.routes.url_helpers.foo_path(f) 
    "Foo <a href='#{foo_path}'>#{f.name}</a> has the wrong mode.".html_safe 
    end 

그것은 잘 작동을하지만 권장 것을 알고있다 이렇게하는 방법은 로케일 파일을 통해서입니다. 내가 다른 모델의 속성을 확인하는거야 때문에 나는 그 문제가 있습니다, 그래서 다음은 작동하지 않습니다

en: 
    activerecord: 
    errors: 
     models: 
     bar: 
      attributes: 
      foo: 
       mode_mismatch: "Foo %{link} has the wrong mode." 

이 작업을 수행하는 올바른 방법은 무엇입니까?

+0

의 문제가되는 link 보간 해당 로케일 문자열을 사용

en: activerecord: errors: messages: mode_mismatch: "Foo %{link} has the wrong mode." 

: FooBaractiverecord.errors.messages 대신 activerecord.errors.models에 그것을 포함하면 mode_mismatch에 대해 동일한 오류 메시지를 공유 할 수 있습니다 'mode_matcher' 메소드가 유효성을 검사하지만 yml 파일에 지정하지 않았다면 – Choco

+0

whoops,'mode_mismatch' 대신'mode_matcher'를 사용하면 똑같은 일이 발생합니다. – stephenmurdoch

+0

오류가 발생했습니다 – Choco

답변

3

ActiveModel은 여러 범위에서 유효성 검사 오류를 찾습니다. 당신이 사용하는

def mode_matcher 
    self.foos.each do |foo| 
    next unless foo.mode == "http" 

    errors.add :base, :mode_mismatch, link: Rails.application.routes.url_helpers.foo_path(f) 
    end 
end 
+0

고마워요! 나는 그것이 지금 어떻게 작동하는지 안다. 굉장해. – stephenmurdoch