Stupid rails question: undefined method in class declaration

I have a user class where I am trying to attach a profile created by a factory. Here is the class:

class User < ActiveRecord::Base
  acts_as_authentic
  has_one :profile

  after_create {self.profile = ProfileFactory.create_profile(self.role)}

end

and the factory is as follows

class ProfileFactory
    def self.create_profile(role)
      String s = "#{role}#{"Profile"}"
      Object.const_get(s).new
    end
end

For some reason, he does not recognize himself as a user. This is the error I get when calling ProfileFactory.create_profile

undefined "role" of the method for #<Class:0x2304218>

The user object has the role: String declared in its migration.

Any help is appreciated.

+3
source share
3 answers

The object Userpassed to the block after_createis passed as a parameter.

class User < ActiveRecord::Base
  after_create do |user|
    user.profile = ProfileFactory.create_profile(user.role)
    user.save
  end
end
+1
source

factory . , .

self, self. - , .

after_create - , , . , (after_create, before_save ..), . , .

:

  after_create {self.profile = ProfileFactory.create_profile(self.role)}

self - , User, .

after_create, , . .

class User < ActiveRecord::Base
  has_one :profile
  after_create :add_profile

  protected

    def add_profile
      self.profile = ProfileFactory.create_profile(role)
    end
end

EmFi, . , , ?

, , . .

. , , . , , , .

+6

- ? - :

class User < ActiveRecord::Base
  has_one :profile
  after_create :add_profile

  protected

    def add_profile
      self.create_profile(:role => self.role)
    end
end

class Profile < ActiveRecord::Base
  belongs_to :user

end

Java?

+1

Source: https://habr.com/ru/post/1720635/


All Articles