如何在rails 3中覆盖模型验证消息

时间:2012-12-28 10:05:09

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我有一个模型 group_question_answer.rb

class GroupQuestionAnswer < ActiveRecord::Base
  belongs_to :group_question
  validates_presence_of :answer 
  validates_presence_of :answer_question    

end

属性answeranswer_question我收到错误消息Group question answers answer can't be blank 我只需要显示answer cant be blank。我甚至尝试添加:message=>"cant be blank",但我仍然没有得到我所需的消息。我可以删除模型名称并且可以只是arrtibute错误消息....

3 个答案:

答案 0 :(得分:4)

class GroupQuestionAnswer < ActiveRecord::Base
  attr_accessible :answer
  validate do |group_question_answer|
    errors.add(:base, "answer can't be blank") if group_question_answer.answer.blank?
  end
end

完美运作

rails c
Loading development environment (Rails 3.2.9)
irb(main):001:0> q = GroupQuestionAnswer.create
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
=> #<GroupQuestionAnswer id: nil, answer: nil, created_at: nil, updated_at: nil>
irb(main):002:0> q
=> #<GroupQuestionAnswer id: nil, answer: nil, created_at: nil, updated_at: nil>
irb(main):003:0> q.save
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
=> false
irb(main):004:0> q.errors
=> #<ActiveModel::Errors:0x007fc2fb325fa8 @base=#<GroupQuestionAnswer id: nil, answer: nil, created_at: nil, updated_at: nil>, @messages={:base=>["answer can't be blank"]}>
irb(main):006:0> q.errors.messages
=> {:base=>["answer can't be blank"]}

<强> =&GT; {:base =&gt; [“答案不能为空白”]}

irb(main):007:0> q = GroupQuestionAnswer.create(answer: "123")
   (0.1ms)  begin transaction
  SQL (9.0ms)  INSERT INTO "group_question_answers" ("answer", "created_at", "updated_at") VALUES (?, ?, ?)  [["answer", "123"], ["created_at", Fri, 28 Dec 2012 11:01:38 UTC +00:00], ["updated_at", Fri, 28 Dec 2012 11:01:38 UTC +00:00]]
   (1.1ms)  commit transaction
=> #<GroupQuestionAnswer id: 1, answer: "123", created_at: "2012-12-28 11:01:38", updated_at: "2012-12-28 11:01:38">
irb(main):008:0> q.errors.messages
=> {}

在我看来,验证方法是完全自定义rails验证的完美方式,并且完全符合您的要求。

答案 1 :(得分:3)

您可以尝试这样:

validates :answer, presence: { message: '<Your message>'}
validates :answer_question, presence: { message: '<Your message>'}

答案 2 :(得分:0)

尝试在config / locales / en.yml文件中添加它们

在那里你可以做这样的事情,

en:
  errors:
    messages:
      answer: answer can't be blank