我有我的模特课
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
在我的控制器中,我正在以两种方式创建Location对象
Location.new(result) #works fine
@post.location.new #get error
为什么在第二种情况下,它寻找带有2个参数的构造函数。我还添加了两个参数的构造函数,但它没有用。
我收到错误
wrong number of arguments (2 for 1)
编辑: 我如何让@ post.location.new工作?
答案 0 :(得分:2)
您正在覆盖Location
的构造函数以获取一个参数,所以现在您必须为每个new
调用提供它。你最好的选择可能不是这样做,或者至少提供一个默认值,如下所示:
def initialize(result = {})
@address = result["address"]
@category = result["category"]
end
要构建空关联,您可以使用
@post.build_location
或
@post.location = Location.new
答案 1 :(得分:0)
是的,对于问题的最后一部分,(2 for 1)表示您提供了两个,但该方法只需要一个。只试一次。