从导轨使用参数的URL地址5查询

问题描述 投票:0回答:2

我怎样才能生成查询的网址

例如http://localhost:3000/articles

我要的是,这个URL可以是负载查询

例如articles?author="author_name"

我应该在我的控制呢?

编辑:article_controller

def index
@articles = Article.all
end

路线

resources :authors
resources :articles
resources :categories

视图

<% @articles.each do |article| %>
  <tr>
    <td><%= article.no_urut %></td>
    <td><%= article.judul_artikel %></td>
    <td><%= article.konten %></td>
    <td><%= article.category.nama_kategori %></td>
    <td><%= article.author.author_name %></td>
    <td><%= link_to 'Show', article %></td>
    <td><%= link_to 'Edit', edit_article_path(article) %></td>
    <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
ruby-on-rails ruby-on-rails-5
2个回答
0
投票

正如雷说,如果添加:

<%= link_to articles_path(author: "name_here") %>

将生成的URL http://localhost:3000/articles?author=name_here

您可能会发现它更容易使用宝石来轻松实现由作者姓名文章搜索,但如果你只是想在你的ArticlesController手动执行此操作:

def index
  if params[:author]
    @author = params[:author]
    @articles = Article.all.where(author: @author)
  else
    @articles = Article.all
  end
end

0
投票

你不需要在控制器做任何事情,因为articles_path轨道URL路径将为http://localhost:3000/articles航线(提供适当的路线)

所以传递任何键值就没事了与articles_path(author: 'author_name')和访问它的控制器行动params[:author_name]

更新:如果你想通过提供名,来获取指标的作者是搜索功能 - 可以用ranksack高效地完成

请参考this看到结果视图

© www.soinside.com 2019 - 2024. All rights reserved.