【问题标题】:Using a Method from Controller in Another Rails在另一个 Rails 中使用控制器中的方法
【发布时间】:2015-04-23 01:12:39
【问题描述】:

我在我的 rails 4 应用上使用 elasticsearch 来搜索我的文章。

但是,当找不到文章时,它会重定向到一个页面,在该页面上提醒用户未找到任何结果,并允许请求页面。而不是说“没有找到结果”,我希望它说“没有找到______的结果”,其中接受搜索栏查询。

我在articles_controller 中定义了一个方法来获取查询,但它不会显示在页面上,因为“无结果页面”使用了不同的控制器。

在这种情况下,将方法拉到另一个控制器或视图上的最佳方法是什么?无法为我正在尝试做的事情找到一个直截了当的答案。非常感谢。

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(查看“未找到结果”页面。使用与文章页面不同的控制器):

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

如您所见,我尝试调用 @userquery 方法以显示在视图页面上,但由于它是在不同的控制器上定义的,因此它没有显示出来。任何建议都会很棒。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 methods elasticsearch controller


    【解决方案1】:

    我建议您从同一个控制器/视图中渲染结果而不是结果。一个很好的干净方法是使用部分。您的视图可能类似于:

    <% if @articles.blank? %>
      <%= render 'no_results' %>
    <% else %>
      <%= render 'results' %>
    <% end %>
    

    然后,您只需创建_no_results.html.erb 并使用您当前的new.html.erb 内容填充它,并对您的名义结果页面执行相同操作(部分_results.html.erb)。

    【讨论】:

    • 正确。这样,您就拥有了所需的所有上下文。
    • 您是否将局部视图与索引视图放在同一文件夹中?看起来应该是app/views/articles
    • 是的,我做到了,我很抱歉我还是 Rails 新手。
    • 你能发布更多代码以及具体错误吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多