简体   繁体   English

如何在错误消息字符串中格式化插值

[英]How to format interpolation within error message string

I have a method in my model that does the following: 我的模型中有一个方法可以执行以下操作:

def price_estimate_range
  if self.upper_price_estimate > self.lower_price_estimate + (lower_price_estimate * (1/10.0))
    errors.add(:base, "Your upper price estimate must not exceed 10% of the lower price estimate. That is #{self.lower_price_estimate + (self.lower_price_estimate * (1/10.0))}")
  end
end

How do I format the interpolation: #{self.lower_price_estimate + (self.lower_price_estimate * (1/10.0))} within the string with number_to_percentage or something similar when it's rendered in my message block? 如何设置插值格式: #{self.lower_price_estimate + (self.lower_price_estimate * (1/10.0))}在字符串中使用number_to_percentage或类似的形式(在消息块中呈现时)?

<% @bid.errors.full_messages.each do |message| %>
  <li><%= message %></li>
<% end %>
def price_estimate_range
  limit = self.lower_price_estimate + (lower_price_estimate * (1/10.0))
  if self.upper_price_estimate > limit
    text = number_with_precision(limit, precision: 2)
    errors.add(:base, "Your upper price estimate must not exceed 10% of the lower price estimate. That is #{text}")
  end
end

Or sprintf the limit, or something like that. 或sprintf限制,或类似的东西。 (if you might have to use that value more than once, calc it one and reuse the result) (如果您可能不得不多次使用该值,请计算一次并重用结果)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM