rails 5、留一个字段怎么只有一条验证信息empty/blank?
In rails 5, how do I only have one validation message if I leave a field empty/blank?
我正在使用 Rails 5. 我的模型中有这个 ...
belongs_to :crypto_currency
validates :crypto_currency, presence: true
问题是当我从表单保存我的模型时,如果我没有为 "Crypto_currency" 字段设置值,则会返回两个错误...
Crypto currency must exist
Crypto currency Please select a value for crypto currency.
这是我的 config/locales/en.yml 文件。我仍然需要弄清楚如何从 "Crypto currency Please select a value for crypto currency." 错误消息中删除 "Crypto currency" 单词,但是您可以清楚地看到我在文件
中只定义了一条错误消息
en:
activerecord:
errors:
models:
user_notification:
attributes:
crypto_currency:
blank: "Please select a value for crypto currency."
如果我的模型字段未输入,如何只有一条错误消息?
编辑: 为回应评论,以下是我显示错误消息的方式
<ul>
<% @user_notification.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
Rails 5 默认需要 belongs_to
关联
belongs_to :crypto_currency
添加验证,因此您不需要自己的。
您可以像这样跳过 belongs_to
默认验证:
belongs_to :crypto_currency, optional: true
或删除您自己的并自定义默认错误消息
尝试像这样更改您的模型:
belongs_to :crypto_currency, optional: true
validates :crypto_currency, presence: true
和
en:
activerecord:
attributes:
user_notification:
crypto_currency: ""
errors:
models:
user_notification:
attributes:
crypto_currency:
blank: "Please select a value for crypto currency."
我正在使用 Rails 5. 我的模型中有这个 ...
belongs_to :crypto_currency
validates :crypto_currency, presence: true
问题是当我从表单保存我的模型时,如果我没有为 "Crypto_currency" 字段设置值,则会返回两个错误...
Crypto currency must exist
Crypto currency Please select a value for crypto currency.
这是我的 config/locales/en.yml 文件。我仍然需要弄清楚如何从 "Crypto currency Please select a value for crypto currency." 错误消息中删除 "Crypto currency" 单词,但是您可以清楚地看到我在文件
中只定义了一条错误消息en:
activerecord:
errors:
models:
user_notification:
attributes:
crypto_currency:
blank: "Please select a value for crypto currency."
如果我的模型字段未输入,如何只有一条错误消息?
编辑: 为回应评论,以下是我显示错误消息的方式
<ul>
<% @user_notification.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
Rails 5 默认需要 belongs_to
关联
belongs_to :crypto_currency
添加验证,因此您不需要自己的。
您可以像这样跳过 belongs_to
默认验证:
belongs_to :crypto_currency, optional: true
或删除您自己的并自定义默认错误消息
尝试像这样更改您的模型:
belongs_to :crypto_currency, optional: true
validates :crypto_currency, presence: true
和
en:
activerecord:
attributes:
user_notification:
crypto_currency: ""
errors:
models:
user_notification:
attributes:
crypto_currency:
blank: "Please select a value for crypto currency."