Rails: How to get the model class name based on the controller class name?

This will do it:

class HouseBuyersController < ApplicationController

  def index
    @model_name = controller_name.classify
  end

end

This is often needed when abstracting controller actions:

class HouseBuyersController < ApplicationController

  def index
    # Equivalent of @house_buyers = HouseBuyer.find(:all)
    objects = controller_name.classify.constantize.find(:all)
    instance_variable_set("@#{controller_name}", objects)
  end

end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)