harshit
harshit

Reputation: 7951

Argument ruby error - wrong number of arguments

I have my model class

class Location < ActiveRecord::Base
 belongs_to :post
 attr_accessor :address, :category,:name,:postcode,:tel

 def initialize(result)

   @address = result["address"]
   @category = result["category"]
 end
end

In my controller I am doing create Location object in two ways

Location.new(result) #works fine
@post.location.new         #get error

Why in second case its looking for constructor with 2 arguments. I also added constructor with two arguments but it didnt work.

I get error

wrong number of arguments (2 for 1)

Edit : How do i make @post.location.new work ?

Upvotes: 0

Views: 1053

Answers (2)

Thilo
Thilo

Reputation: 17735

You're overwriting the constructor for Location to take exactly one argument, so now you'll have to provide it with each call of new. Your best bet is probably not to do that, or at least to provide a default, something like this:

def initialize(result = {})
   @address  = result["address"]
   @category = result["category"]
end

To build an empty association, you can then use

@post.build_location

or

@post.location = Location.new

Upvotes: 2

kikuchiyo
kikuchiyo

Reputation: 3421

Yes, for the last part of your question, ( 2 for 1 ) means you provided two, but the method only takes one. Try only one.

Upvotes: 0

Related Questions