mercredi 22 avril 2015

Using a Method from Controller in Another Rails

I am using elasticsearch on my rails 4 app to search through my articles.

However, when an article is not found it redirects to a page where it alerts the user that no results are found, and allows to request a page. Instead of it saying "no results found" I want it to say "no results for ______ found" in which is takes the search bar query.

I have defined a method in the articles_controller in order to get the query but it won't show up on the page since the "no results page" uses a different controller.

What would be the best way to pull the method onto another controller or view in this case? Having trouble finding a straight forward answer for what I am trying to do. Thank you very much.

articles_controller:

  def index

    if params[:query].present?
      @articles = Article.search(params[:query], misspellings: {edit_distance: 1})
    else
      @articles = Article.all
    end

    if @articles.blank?
      return redirect_to request_path
    end

    get_query
  end

  private

  def get_query
    @userquery = params[:query]
  end

new.html.erb (view for "no results found" page. Uses a different controller than articles page):

<body class="contactrequest">
 <div class="authform" style="margin-top:15px">
  <%= simple_form_for @request, :url => request_path do |f| %>

  <h3 style = "text-align:center; color:red;">No results found. <%= @userquery %></h3>
  <h1 style = "text-align:center; color:black;">Request a Page</h1>
  <h5 style = "text-align:center; color:black; margin-bottom: 25px;">Our experts will gather the information,<br> and have your page us ASAP!</h5>

  <%= f.error_notification %>

  <div class="form-group">

    <%= f.text_field :email, placeholder: 'Email', :autofocus => true, class: 'form-control' %>
  </div>
  <div class="form-group">

    <%= f.text_field :subject, placeholder: 'Item / Page Requested', class: 'form-control' %>
  </div>
  <div class="form-group">

    <%= f.text_area :content, placeholder: 'Any additional details...', class: 'form-control', :rows => '5' %>
  </div>

    <%= f.submit 'Request it', :class => 'btn btn-lg btn-danger btn-block' %>

<% end %>

As you can see I've tried calling that @userquery method to display on the view page, but it doesn't show up since it's defined on a different controller. Any recommendations would be awesome.

Aucun commentaire:

Enregistrer un commentaire