daiikota
daiikota

Reputation: 133

before_destroy definition NoMethodError

hey I'm having a little trouble with this function

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

it gives me this error NoMethodError: undefined method `group' for #Group id: 18, so what is wrong with my definition?

the error message

    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'

Upvotes: 0

Views: 489

Answers (1)

yuяi
yuяi

Reputation: 2715

Your error doesn't make sense, since you're calling #group on user and not on group.

However, I believe that

u.group = self.first

will not work as you intend it to, since #first is a class method, and self here is an instance. Try:

u.group = self.class.first

or simply:

u.group = Group.first

Upvotes: 1

Related Questions