2

我有一个模型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",但我仍然没有收到我需要的消息。我怎样才能删除模型名称,并且可以只显示错误消息....

4

3 回答 3

5
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"]}

=> {:base=>["答案不能为空"]}

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
=> {}

在我看来 validate 方法是完全自定义 Rails 验证的完美方法,这正是你所要求的。

于 2012-12-28T10:14:08.387 回答
3

你可以这样尝试:

validates :answer, presence: { message: '<Your message>'}
validates :answer_question, presence: { message: '<Your message>'}
于 2012-12-28T10:10:30.787 回答
0

尝试将它们添加到您的 config/locales/en.yml 文件中

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

en:
  errors:
    messages:
      answer: answer can't be blank
于 2012-12-28T10:39:57.017 回答