简体   繁体   中英

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:

app/controllers/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. This would require me to make the search object globally available, and I am not sure how to do that. 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. 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.

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.

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...

Add this to your 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 ); 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:

    <% @search = Search.new %>
    <%= form_for @search do |form| %>
      <%= form.text_field :query, placeholder: "Search for a Picture" %>
    <% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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