如何设置数据库接受货币值?

时间:2014-01-20 23:05:13

标签: mysql ruby sinatra sequel

我正在使用Sinatra撰写Sequel个应用程序。我第一次尝试添加货币。在线查看之后我使用Numeric作为值,当然不用说我需要一个小数点精度。

我知道在MySQL中,NumericDecimal是相同的。所以我想知道我在这里做错了什么。我觉得我需要以某种方式定义小数点。这是我的模特:

# Contracts table: Here the users can define their contracs
DB.create_table?(:contracts, engine: 'InnoDB') do
    primary_key :id
    Integer :user_id,   null: false
    String  :name,      null: false
    String  :description
    Numeric :cost,      null: false
end

每当我尝试提交带小数点的值时,我都会收到以下错误,我认为这是一个验证错误。我还没有明确地使用验证,所以我认为它是Sequel或MySQL特有的。

enter image description here

如何更改模型以允许我添加小数值?

编辑:根据要求,我添加了我的控制器(路由)文件:

class Metro < Sinatra::Base
    get "/user_add_contract" do
        protected!
        haml :user_add_contract
    end

    post "/user_add_contract" do
        protected!
        user = session['name']
        begin
            uid = User.first(username: user)
            Contract.create(user_id: uid[:id], name: params['name'], description: params['description'], cost: params['cost'].to_f)
            redirect '/user_list_contract'
        rescue Exception => e
            @error = e
            haml :details_error
        end


    end

end

和HAML(观点):

%form(action="/user_add_contract" method="post")
  %fieldset
    %legend Φόρμα Νέου Συμβολαίου
    %div{class: 'column1of2'}
      %ul
        %li
          %label(for="name")Ονομασία:
          %input#name(name="text" name="name")
        %li
          %label(for="description")Περιγραφή:
          %textarea.email#description(type="text" name="description")
        %li
          %label(foor="cost")Κόστος:
          %input#cost(type="number" name="cost")
        %li
          %input(type="submit" value="Εγγραφη") ή <a href="/panel">Ακύρωση</a>

感谢

1 个答案:

答案 0 :(得分:1)

相关答案:How to handle floats and decimal separators with html5 input type number

这里的step=""属性默认为1,这意味着它将截断小数点后的所有内容(或者根据设置的方式以及您使用的浏览器来回放错误)

尝试在输入元素上设置step="0.01",假设您只想到最近的分数,看看是否有效。代码中的其他所有内容都很好。*

  • 您的费用<label>
  • 除了“foor”而不是“for”之外