[英]Rails: How can I make an object available in all views?
I have a search
object which is created in my Galleries controller and displayed in my Galleries View: 我有一个在我的Galleries控制器中创建并显示在我的Galleries视图中的
search
对象:
app/controllers/galleries_controller.rb 应用程序/控制器/ galleries_controller.rb
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
This object represents a search bar. 该对象代表搜索栏。 I want to move the search bar into my
layouts/application.html.erb
view and make it available on all pages in the header. 我想将搜索栏移到我的
layouts/application.html.erb
视图中,并使其在标题的所有页面上可用。 This would require me to make the search
object globally available, and I am not sure how to do that. 这将要求我使
search
对象全局可用,但我不确定如何做到这一点。 I tried sticking in ApplicationController and thought that would make it available in all views since everything inherence from there, but it didn't work. 我尝试坚持使用ApplicationController并认为这将使它在所有视图中都可用,因为所有继承都源于此,但它没有用。 How can I make an object available in all views?
如何使对象在所有视图中可用?
You can do it with a before_action
(aka. before_filter
) in the ApplicationController
, from which all your controllers should inherit. 你可以用做
before_action
(亦称before_filter
中) ApplicationController
,从所有的控制器应该继承。
class ApplicationController < ActionController::Base
before_action :make_search
def make_search
@galleries = Gallery.all
@search = Search.new
end
end
This will make the function run before every action. 这将使函数在执行每个操作之前运行。
You can use skip_before_action :make_search
to disable it in a specific controller, if you need to, or skip_before_action :make_search, only: :index
to disable it for only the index
action for a controller. 如果需要,可以使用
skip_before_action :make_search
在特定控制器中禁用它,或者使用skip_before_action :make_search, only: :index
仅对控制器的index
操作禁用它。
If you only want this for a few controllers, you could define make_search
in the ApplicationController
, and put the before_action :make_search
in the controllers for which you want to enable it... 如果只需要几个控制器,可以在
ApplicationController
定义make_search
,然后将before_action :make_search
放入要启用它的控制器中。
Add this to your ApplicationController
: 将此添加到您的
ApplicationController
:
def search
@search ||= Search.new
end
def galleries
@galleries ||= Gallery.all
end
You then use the function ( search
) in your views instead if the instance variable @search
); 然后,如果实例变量
@search
),则在视图中使用该函数( search
); the ||=
makes sure the code is executed only once (thus saving database queries). ||=
确保代码仅执行一次(从而节省了数据库查询)。
You can make the object globally available by breaking MVC and just create the object inside the view: 您可以通过破坏MVC使对象在全局范围内可用,而只需在视图内部创建对象即可:
<% @search = Search.new %>
<%= form_for @search do |form| %>
<%= form.text_field :query, placeholder: "Search for a Picture" %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.