gpt4 book ai didi

ruby-on-rails - 如何覆盖 Rails 3 中的模型验证消息

转载 作者:行者123 更新时间:2023-12-02 07:38:09 25 4
gpt4 key购买 nike

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

最佳答案

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 验证的完美方式,它完全符合您的要求。

关于ruby-on-rails - 如何覆盖 Rails 3 中的模型验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14067833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com