Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the model name in a concern (or in a module)?

I have the following concern in my rails app:

module Authenticable
  extend ActiveSupport::Concern

  included do
    # ...
  end

  module ClassMethods
    def quoted_table_name
      self.class.name.downcase.pluralize # returns "classes"
    end
  end
end

If I have a user class:

class User
  include Authenticable
end

then I could like User.quoted_table_name to return "users". Currently, User.quoted_table_name returns "classes". I also tried to the following, but nothing changed.

def quoted_table_name
  Proc.new { self.class.name.downcase.pluralize }.call
end
like image 414
Max Avatar asked Jul 01 '13 19:07

Max


1 Answers

Try the following:

module Authenticable
  ...

  module ClassMethods
    def quoted_table_name
      name.downcase.pluralize # returns "users"
    end
  end
end

self.class.name.downcase.pluralize does not work, because we already operate on the class-side of the User-class. When asking the User-class for its class, Class is returned. Class.name.downcase.pluralize, however, is "classes".

like image 161
tessi Avatar answered Oct 18 '22 17:10

tessi