简体   繁体   English

Rails如何跨所有控制器访问模型?

[英]Rails how to access a model across all controllers?

If I have a questions controller and a question model, and I want to access a particular question on a, say, static welcome page, how can I reference a particular question on an action not associated with the question controller? 如果我有问题控制器和问题模型,并且我想在静态欢迎页面上访问特定问题,那么如何在与问题控制器无关的操作上引用特定问题? I'm having difficulty figuring out how to reference models everywhere, with a user I think this can be done with a cookie or something? 我很难搞清楚如何在任何地方引用模型,用户我认为这可以用cookie或其他东西来完成? But not sure about questions, I'm new to Rails so thanks! 但不确定问题,我是Rails的新手,谢谢!

Maybe I didn't understand but... 也许我不明白但......

All models are accessible from all controllers. 所有型号均可从所有控制器访问。 You only need to get it (@question = Question.find(...)) 你只需要得到它(@question = Question.find(...))

Controllers and views can access any / all of your models. 控制器和视图可以访问任何/所有模型。

The controller accesses models via various ActiveRecord APIs: 控制器通过各种ActiveRecord API访问模型:

User.find(params[:user_id])

The view then accesses this data via instance variables: 然后视图通过实例变量访问此数据:

# Controller sets instance var
@user = User.find(params[:user_id])

<%# View uses instance var %>
<h1><%= @user.first_name %></h1>

Read these Rails guides: 阅读这些Rails指南:

  1. http://guides.rubyonrails.org/layouts_and_rendering.html http://guides.rubyonrails.org/layouts_and_rendering.html
  2. http://guides.rubyonrails.org/action_controller_overview.html http://guides.rubyonrails.org/action_controller_overview.html

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

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