简体   繁体   中英

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM