0

I have a Product.rb model in my Rails app, and it has a :title attribute and a :price attribute. From the Rails console I can successfully create an instance of one of these models, but I'm having trouble passing values for the :title and :price. Here's my products_controller:

class ProductsController < ApplicationController

def create

@product = Product.create(
  :name = params[:name],
  :price = params[:price]
  )
end

end

This is the command I use to create an instance:

Product.create("name", 123)

The :name attribute is set to be text and the :price attribute to be an integer. But when I hit enter this is what I got:

ArgumentError: wrong number of arguments (2 for 0..1) 

I haven't written any Rails since before v4 and I'm a bit rusty. Anyone know the problem?

1
  • 3
    It should be :name => params[:name] etc, arrow, not assignment. Commented Jul 1, 2014 at 22:19

1 Answer 1

1

You're missing the > in your hash rockets.

Try this:

class ProductsController < ApplicationController

  def create
    @product = Product.create(
      :name => params[:name],
      :price => params[:price]
    )
  end
end

Incidentally, unless you're doing something particularly special, it looks like you're probably doing the form in a non-conventional way.

You should be using a form helper along these lines in your view:

<%= form_for @product do |f| %>
  ...

And then in your controller, creating the product as follows:

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

  if @product.save
    ...
end

UPDATE: As pointed out by @Iceman, if you're using Rails 4 you'll need to use Strong Parameters for the params used for mass-assignment.

Typically you'd create a private method to handle these, and call that within your object creation/update method calls:

class ProductsController < ApplicationController
  def create
    @product = Product.new(product_params)

    if @product.save
      ...
  end

  private

  def product_params
    params.require(:product).permit(:name, :price)
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

You'll need strong_parameters if this is Rails 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.