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

时间:2015-01-22 04:23:56

标签: ruby-on-rails ruby activerecord string-interpolation

我的模型中有一个方法可以执行以下操作:

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

如何在带有number_to_percentage的字符串中格式化插值:#{self.lower_price_estimate + (self.lower_price_estimate * (1/10.0))}或在我的消息块中呈现的类似内容?

<% @bid.errors.full_messages.each do |message| %>
  <li><%= message %></li>
<% end %>

1 个答案:

答案 0 :(得分:0)

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

或sprintf极限,或类似的东西。 (如果您可能不得不多次使用该值,请将其计算一次并重复使用结果)

相关问题