简体   繁体   English

Rails控制器如何访问模型?

[英]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. Rails指南教程中articles控制器可以神奇地访问Article模型。 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? 还是所有控制器都可以访问他们选择的任何模型?

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. 这不是魔术,并且不仅限于控制器和模型,Rails(取决于您使用的版本)会自动加载app/目录下的每个类和模块,这意味着您可以从整个其他任何类访问任何类项目。 So if you add a new directory and file under the app/ directory, like app/services/foo_bar.rb . 因此,如果您在app/目录下添加新目录和文件,例如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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM