before_destroy定义NoMethodError

时间:2012-12-05 21:26:09

标签: ruby-on-rails ruby nomethoderror

嘿,我对这个功能有点麻烦

class User < ActiveRecord::Base
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :users
  attr_accessible :name
  validates_presence_of :name

  before_destroy :set_default_group

  private
  def set_default_group
    self.users.each do |u| 
      puts u # prints out <User:0x007fd678a85cb8>
      u.group = self.first
      u.save    
    end
  end
end

它给了我这个错误NoMethodError:#Group id:18的未定义方法`group',那么我的定义有什么问题?

错误消息

    NoMethodError: undefined method `group' for #<Group id: 18>
from /Users/.../.rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.8/lib/active_model/attribute_methods.rb:407:in `method_missing'
    from /Users/.../.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/attribute_methods.rb:149:in `method_missing'
    from /Users/.../Developer/rails/.../app/models/group.rb:12:in `block in set_default_group'
    from /Users/.../.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/associations/collection_proxy.rb:89:in `each'
    from /Users/.../.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/associations/collection_proxy.rb:89:in `method_missing'
    from /Users/.../Developer/rails/.../app/models/group.rb:10:in `set_default_group'

1 个答案:

答案 0 :(得分:1)

您的错误没有意义,因为您在用户上而不在上调用 #group

但是,我相信

u.group = self.first

不会像你想要的那样工作,因为 #first 是一个类方法, self 这里是一个实例。尝试:

u.group = self.class.first

或简单地说:

u.group = Group.first