Roberto Pezzali
Roberto Pezzali

Reputation: 2504

Rails, undefined method in Class but method is present

I'm trying to solve a strange issue. I'm extending ActiveRecord using a module.

module StringyAssociationIds

  def stringy_ids(association)
    define_method("stringy_#{association}_ids=") do |comma_seperated_ids|
      self.send("#{association}_ids=", comma_seperated_ids.to_s.split(","))
    end

    define_method("stringy_#{association}_ids") do
      send("#{association}_ids").join(",")
    end
  end

end

ActiveRecord::Base.extend(StringyAssociationIds) 

I have a class "Gate" where I have an association.

class Gate < ActiveRecord::Base
  include Productable
  stringy_ids :product
end

The association is defined with a join table:

module Productable
  extend ActiveSupport::Concern

  included do
    has_many :productable_products, as: :productable
    has_many :products, through: :productable_products
  end

end

When I try to create a new Gate I have an error:

undefined method `stringy_ids' for #<Class:0x007f91e12bb7e8>

Where is my fault?

Edit: I try also to add an extension inside the lib directory (autoloaded by application.rb)

module ActiveRecordExtension

  extend ActiveSupport::Concern

  def stringy_ids(association)
    define_method("stringy_#{association}_ids=") do |comma_seperated_ids|
      self.send("#{association}_ids=", comma_seperated_ids.to_s.split(","))
    end

    define_method("stringy_#{association}_ids") do
      send("#{association}_ids").join(",")
    end
  end

end

# include the extension 
ActiveRecord::Base.send(:include, ActiveRecordExtension)

I try also in console:

ActiveRecordExtension.instance_methods
 => [:stringy_ids]

So my extension is loaded...

Upvotes: 3

Views: 1465

Answers (2)

Jaehyun Shin
Jaehyun Shin

Reputation: 1602

StringyAssociationIds is not extended.
Actually, ActiveRecord::Base.extend(StringyAssociationIds) does not run. Move this code in config/initializer

Upvotes: 0

sawa
sawa

Reputation: 168269

Your class method stringy_ids is defined on ActiveRecord::Base, not Gate. Unlike instance methods, class methods are not inherited because the singleton class of Gate is not a subclass of the singleton class of ActiveRecord::Base.

Upvotes: 3

Related Questions