简体   繁体   中英

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?

<% @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. (if you might have to use that value more than once, calc it one and reuse the result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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