stackjlei
stackjlei

Reputation: 10035

How does a Rails controller get access to a model?

In the Rails guide tutorial, the articles controller magically gets access to the Article model. Is this done for you automatically as long the controller and model name matches? Or do all controllers have access to any model of their choosing?

Upvotes: 0

Views: 955

Answers (1)

John Hayes-Reed
John Hayes-Reed

Reputation: 1428

This is not magical, and this is not limited to controllers and models, Rails (depending on the version you are using) autoloads every class and module under the app/ directory, meaning you have access to any class from any other class in the whole project. So if you add a new directory and file under the app/ directory, like app/services/foo_bar.rb. You can also access that from your controller, or your model, or from another service class, eg:

class ArticlesController < ApplicationController
  def new
    @article = Article.new
    FooBar.do_something(@article)
  end
end

or:

class Article < ApplicationRecord
  #....

  private

  def lets_all_foo_our_bars
    FooBar.foo_my_bar
  end
end

Upvotes: 4

Related Questions