1

我在使用money-rails gem 将值保存到我的数据库时遇到问题。每当我尝试在文本框中输入一个带美分的值(即 20.22)时,它都会提示我“请输入一个有效值。两个最接近的值是 20 和 21”。

模型:

class VideoGame < ActiveRecord::Base

    monetize :loose_price_cents, with_model_currency: :price_currency
    monetize :cib_price_cents, with_model_currency: :price_currency
    monetize :new_price_cents, with_model_currency: :price_currency

end

_form.html.erb:

<%= form_for(@video_game) do |f| %>
  <% if @video_game.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@video_game.errors.count, "error") %> prohibited this video_game from being saved:</h2>

      <ul>
      <% @video_game.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :game %><br>
    <%= f.text_field :game %>
  </div>
  <div class="field">
    <%= f.label :loose_price %><br>
    <%= f.number_field :loose_price %>
  </div>
  <div class="field">
    <%= f.label :cib_price %><br>
    <%= f.number_field :cib_price %>
  </div>
  <div class="field">
    <%= f.label :new_price %><br>
    <%= f.number_field :new_price %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

控制器更新功能:

def update
      respond_to do |format|
      if @video_game.update(video_game_params)
        format.html { redirect_to @video_game, notice: 'Video game was successfully updated.' }
        format.json { render :show, status: :ok, location: @video_game }
      else
        format.html { render :edit }
        format.json { render json: @video_game.errors, status: :unprocessable_entity }
      end
    end
  end

我已经进入rails控制台并手动更改了值,但它似乎基于数据库值的错误(db值= 2011美分,错误=“请输入一个有效值。两个最接近的值是20.11和21.11。 ")。

任何意见,将不胜感激!

编辑:我想通了。通过在 number_field 方法的末尾添加“step: 0.01”,它允许您将值增加 .01 而不是默认情况下的 1。它应该看起来像这样:

<%= form_for(@video_game) do |f| %>
  <% if @video_game.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@video_game.errors.count, "error") %> prohibited this video_game from being saved:</h2>

      <ul>
      <% @video_game.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :game %><br>
    <%= f.text_field :game %>
  </div>
  <div class="field">
    <%= f.label :loose_price %><br>
    <%= f.number_field :loose_price, step: 0.01 %>
  </div>
  <div class="field">
    <%= f.label :cib_price %><br>
    <%= f.number_field :cib_price, step: 0.01 %>
  </div>
  <div class="field">
    <%= f.label :new_price %><br>
    <%= f.number_field :new_price, step: 0.01 %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
4

0 回答 0