linkyndy
linkyndy

Reputation: 17928

Get model for current controller

I am building a controller concern, and inside it I need a reference to the current controller's related model. So, if I have something like:

class UsersController < ApplicationController
  include Concern
end

module Concern
  extend ActiveSupport::Concern

  def bla
    self.model # ??
  end
end

I would like in bla to get a reference of the current model, so that when I include Concern in UserController, I get a User reference.

Is this possible in Rails?

Upvotes: 4

Views: 3221

Answers (5)

Alexaner Tipugin
Alexaner Tipugin

Reputation: 507

Add following method to your concern:

def resource
  resource_name = self
    .class
    .name
    .underscore
    .gsub(/_controller$/, '')
    .singularize

  self.instance_variable_get("@#{resource_name}")
end

Now you can retrieve your resource through instance var (i.e. @user).

Upvotes: 0

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do this, but only if you have followed Convention over Configuration for naming the controller and model

controller_name.classify.constantize

Upvotes: 7

Sachin R
Sachin R

Reputation: 11876

Inside your controller action call like that

self.class.name.sub("Controller", "").singularize.constantize

Upvotes: 0

tompave
tompave

Reputation: 12427

You can infer it from the name of the controller, but it's not 100% reliable, and it will only make sense for RESTful controllers.

This means that if you have an ArticlesController with the default RESTful routes (index, show, new, ecc), it is safe to assume that the related model will be Article. Likewise, you can assume that a RESTful UsersController will be about the User model.

This of course doesn't make sense for non RESTful controller. You could have a GraphPollingController, for example, that does not rely on a specific model.

Upvotes: 1

shivam
shivam

Reputation: 16506

You can access use controller_name to get the name of controller and then use classify to get class name.

In short:

controller_name.classify

Upvotes: 1

Related Questions