Ruby on rails Rails:如何使对象在所有视图中都可用?
我有一个Ruby on rails Rails:如何使对象在所有视图中都可用?,ruby-on-rails,Ruby On Rails,我有一个搜索对象,该对象在我的库控制器中创建,并显示在我的库视图中: class GalleriesController < ApplicationController def index @galleries = Gallery.all @search = Search.new end app/controllers/galleries\u controller.rb class GalleriesController < ApplicationContr
搜索
对象,该对象在我的库控制器中创建,并显示在我的库视图中:
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
app/controllers/galleries\u controller.rb
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
class GalleriesController
此对象表示搜索栏。我想将搜索栏移动到我的
layouts/application.html.erb
视图中,并使其在标题中的所有页面上可用。这需要我使搜索
对象全局可用,我不知道如何做到这一点。我试着坚持使用ApplicationController,并认为这将使它在所有视图中都可用,因为从那里一切都是固有的,但它不起作用。如何使对象在所有视图中都可用?您可以通过断开MVC使对象全局可用,只需在视图中创建对象即可:
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
<% @search = Search.new %>
<%= form_for @search do |form| %>
<%= form.text_field :query, placeholder: "Search for a Picture" %>
<% end %>
您可以使用
应用程序控制器中的before\u action
(也称为before\u filter
)执行此操作,所有控制器都应从中继承
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
class ApplicationController < ActionController::Base
before_action :make_search
def make_search
@galleries = Gallery.all
@search = Search.new
end
end
class ApplicationController
这将使函数在每次操作之前运行
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
如果需要,可以使用skip\u before\u action:make\u search
在特定控制器中禁用它,或者使用skip\u before\u action:make\u search,only::index
仅在控制器的index
操作中禁用它
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
如果您只希望对少数控制器使用此功能,可以在ApplicationController
中定义make\u search
,并将放在\u操作之前:make\u search
放在要启用它的控制器中…将其添加到ApplicationController
:
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end
def search
@search ||= Search.new
end
def galleries
@galleries ||= Gallery.all
end
如果实例变量@search
),则在视图中使用函数(search
);||=
确保代码只执行一次(从而保存数据库查询)
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
@search = Search.new
end