dwilbank
dwilbank

Reputation: 2520

Is there a better 'rails' way of making this rename?

Got this ActiveRecord puzzle, and no one can figure out a better method of extracting the table "students" from self (self is Student).

def self.all
  p self                  # = Student
  Database::Model.execute("SELECT * FROM #{self.to_s.downcase + "s"}").map do |row|
    self.new(row)
  end
end

Is this string manipulation the best way?

Upvotes: 0

Views: 48

Answers (2)

Amadan
Amadan

Reputation: 198368

If I am not mistaken about your intentions, Student.all is what you would normally do.

If you're wondering about how Student becomes "students", it basically involves .class.name.downcase.pluralize (if you keep the default table name). pluralize is quite a bit smarter than just adding "s" to a string.

Upvotes: 1

bdx
bdx

Reputation: 3516

It looks like you're adding this method to a model to get a string reflecting the table name the model is using. Maybe.

If so, you could do this:

def self.all
  table_name
end

Or, because that's just effectively creating an alias, you could do:

ModelName.table_name

Upvotes: 1

Related Questions