Overriding association getters

Hi! I saw that i documentation here - ActiveRecord::Associations::ClassMethods

Overriding generated methods

Association methods are generated in a module that is included into the model class, which allows you to easily override with your own methods and call the original generated method with super. For example:

class Car < ActiveRecord::Base
  belongs_to :owner
  belongs_to :old_owner
  def owner=(new_owner)
    self.old_owner = self.owner
    super
  end
end

If your model class is Project, the module is named Project::GeneratedFeatureMethods. The GeneratedFeatureMethods module is included in the model class immediately after the (anonymous) generated attributes methods module, meaning an association will override the methods for an attribute with the same name.

Now this is my model

class Business < ActiveRecord::Base belongs_to :category, class_name: ‘BusinessCategory’, foreign_key: ‘business_category_id’

def category

super || BusinessCategory.new(name: ‘other’)

end

end

``

Why it keeps throwing

super: no superclass method `category' for #<Business:0x000001023014b8>

``

? Am i missing something?

Possibly because AR::Base has no idea about your renaming of that association. Try calling that method business_category instead, or call business_category instead of super. (Just don’t do both,)

Hey, but i did not rename it. My model hasn’t methods called busyness_category! I though AR generates them according to first argument to ‘belongs_to’ method, rather than from foreign key name

Now this is my model

class Business < ActiveRecord::Base belongs_to :category, class_name: ‘BusinessCategory’, foreign_key: ‘business_category_id’

def category

super || BusinessCategory.new(name: ‘other’)

end

end

``

Why it keeps throwing

super: no superclass method `category' for #<Business:0x000001023014b8>

``

? Am i missing something?

Which version of rails?

Fred

My rails version is 4.2.2.

My rails version is 4.2.2.

Weird - I created a fresh rails app, added a business model like yours and it works fine. I’d recommended doing the same and seeing whether you can isolate what it is about your app that is different (for example is Business::GeneratedAssociationMethods in the ancestor chain for business? What does Profile::GeneratedAssociationMethods.instance_methods look like?)

Fred

Oh yeah, this is because of one gem i use that extends AR in that way. Thanks that you set up fresh app, that helped me.