complete_morons
complete_morons

Reputation: 843

Rails + Postgresql: data not saved first time

The first time I try to submit the form I get the error saying

"Price is not a valid number"

It's OK the second time I try to submit it (with the same valid data in :price field). If I don't add validation in the model, then the form is submitted, but value of price is not saved.

What could be going on? Is there something special about .decimal field?

db schema:

t.decimal  "price"

model

validates :price, numericality: { :greater_than => 0, :less_than_or_equal_to => 100000000 }

form view file

<%= f.number_field :price, class: "short red" %>

controller

  def new
    @product = Product.new
  end


  def create
    @product = Product.new(product_params)
      if @product.save
        redirect_to @product
      else
        render :new
      end
  end

private

def product_params
  params.require(:product).permit(:name, :description, :image, :price, :user_id)
end

logs

Started POST "/products" for xxx.132 at 2014-10-15 22:56:51 +0000
Processing by ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"abte/LtO0T/ZtSXQIuXVVjjUvwHw5jDUJ1yIKCOWRx2=", "product"=>{"name"=>"", "description"=>"", "user_id" =>"1"}, "commit"=>"Submit"}

Upvotes: 0

Views: 83

Answers (2)

MicRum
MicRum

Reputation: 1721

Try to change your migration to:

t.decimal :price, precision: 8, scale: 2  #for example

Then, change validation to:

validates :price, numericality: {greater_than_or_equal_to: 0.01, :less_than_or_equal_to => 100000000 }

In PostgreSQL next implementations behavior with :decimal columns:

PostgreSQL: :precision [1..infinity], :scale [0..infinity]. No default.

I hope, this example from "Agile Web Development with Rails 4" help you to understand validation of decimal numbers:

it’s possible to enter a number such as 0.001 into this field. Because the database stores just two digits after the decimal point, this would end up being zero in the database, even though it would pass the validation if we compared against zero. Checking that the number is at least 1 cent ensures only correct values end up being stored.

Upvotes: 0

Dan Laffan
Dan Laffan

Reputation: 1554

Some things you can check:

  1. The snippet from your form starts f.number_field. Check that you are using something like <%= form_for(@product) do |f| %> at the top of the form.

  2. Try to create a product using the rails console.

  3. In the rails console, try something like this:

    > p = Product.new
    > p.valid?
    #=> TRUE or FALSE should appear
    > p.errors.full_messages.to_sentence
    # you should see a full list of all failed validations from your Product model
    

If these don't help, try pasting in the entire product_controller.rb and _form.html.erb files into your question, and I'll take a look again.

Upvotes: 1

Related Questions