John Doe
John Doe

Reputation: 13

Insert Query is Wrong on Rails

So i am trying to learn Ruby on Rails and i tried to code simple product creation to database but rails only executes the insert query with only created_at and updated_at values. Here is my products_controller's create action ;

def create
    @product = Product.new(params[:product_params])

    @product.save
    redirect_to @product
end

private 
    def product_params
        params.require(:product).permit(:title, :price)
    end

Here is my new.html.erb under products folder ;

<%= form_with scope: :product ,url:products_path, local: true do |form| %>
<p>
 <%= form.text_field :title %>
</p>

<p>
  <%= form.text_field :price %>
</p>

<p>
<%= form.submit %>

<% end %>

And this is the SQL query executed by Rails looking to Rails Server

Started POST "/products" for 127.0.0.1 at 2018-12-04 16:44:52 +0300 Processing by ProductsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"9Z4aFNpMv+uUPXx+LkHoOtYpWae/8tIOCQ3Jt47AFScp/vVHTWI+G4d6CjHqBz6t5L5UR57I7Gh7bUWog1Dqow==", "product"=>{"title"=>"brokoli", "price"=>"3434"}, "commit"=>"Save Product"} (0.2ms) BEGIN ↳ app/controllers/products_controller.rb:8 Product Create (0.3ms) INSERT INTO products (created_at, updated_at) VALUES ('2018-12-04 13:44:52', '2018-12-04 13:44:52') ↳ app/controllers/products_controller.rb:8 (5.4ms) COMMIT ↳ app/controllers/products_controller.rb:8 Redirected to http://localhost:3000/products/12 Completed 302 Found in 25ms (ActiveRecord: 7.4ms)

Upvotes: 1

Views: 154

Answers (2)

Giridharan
Giridharan

Reputation: 568

def create @product = Product.new(product_params) @product.save redirect_to @product end private def product_params params.require(:product).permit(:title, :price) end

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

You don't do

@product = Product.new(params[:product_params])

You do

@product = Product.new(product_params)

The product_params is a method that returns the white-listed params entries.

Upvotes: 2

Related Questions