Anthony
Anthony

Reputation: 35928

how to access a method in a model from a controller in rails

I want to put logic in the model rather than controller.

class UsersController < ApplicationController
  def somemethod
    d = User.methodinmodel
  end
end

class User < ActiveRecord::Base

  def methodinmodel
    "retuns foo"
  end
end

I get an error that there is no methodinmodel for the User model.

Why?

Upvotes: 1

Views: 73

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

If you want to be able to call methodinmodel on the User class in general rather than a specific user, you need to make it a class method using self:

class User < ActiveRecord::Base
  def self.methodinmodel
    "returns foo"
  end
end

Your current method definition would only work if you called it on a user:

@user = User.create!
@user.methodinmodel  # Works.
User.methodinmodel   # Doesn't work.

Using the new implementation using self would allow you to call it like:

User.methodinmodel   # Works.

Upvotes: 1

Related Questions