Rails活動記錄——當關聯模型中有一個初始化方法時,如何使用構建?

[英]Rails Active Record - How to use build when there is an initialize method in associated model?


I have a model called "User" with has many association to "Address" model.

我有一個叫做“用戶”的模型,有很多關聯到“地址”模型。

When I do User.new.addresses.build, I am getting following error,

當我做User.new.addresses。構建,我有以下錯誤,

    ArgumentError: wrong number of arguments (1 for 0)
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `initialize'
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `new'
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `build_association'
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:423:in `build_record'
    from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:102:in `build'
    from (irb):10

This happens when i add an initialize method in Address model.

當我在地址模型中添加一個initialize方法時,就會發生這種情況。

Any help is highly appreciated...

非常感謝您的幫助……

EDITED:

編輯:

There are no arguments to the initialize method and it looks like this

初始化方法沒有參數,它是這樣的

class Address < ActiveRecord::Base
  attr_accessor :test

  def initialize
    test = "manu"
  end
end

2 个解决方案

#1


1  

It's not recommended to override the initialize method of an ActiveRecord inherited class. Use after_initialize callback if you want to add your custom initialization. See the rails api for all the ActiveRecord callbacks.

不建議重寫ActiveRecord繼承類的initialize方法。如果要添加自定義初始化,請使用after_initialize回調。查看所有ActiveRecord回調的rails api。

#2


2  

after_initialize hook should serve your purpose

after_initialize鈎子應該符合您的目的

class Address < ActiveRecord::Base
  attr_accessor :test
  after_initialize :init

  def init
    @test = "manu"
  end
end

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/09/15/72993acb64e15c1daf611e6586320dbb.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com