如何在Ruby on Rails中按标题排序和显示?

时间:2016-12-05 18:53:23

标签: ruby-on-rails ruby

过去几天我一直试着没有运气的例子。 我有一个名为Article的表,其中包含bullet,powder和calibertitle等列。我设置了一个表格,我可以在其中输入子弹牌,粉品牌,口径等特定细节。

我正在使用SQLite。

如何搜索标题中的特定单词,如果标题中包含该单词,则只显示标题和相应的信息?

我可以列出所有数据,但我不确定如何对其进行排序。我还想按字母顺序列出数据。

另外,如果我创建了另一个控制器,是否可以在新控制器下列出/显示相同的列?

/views/articles/index.html.erb

<h1>Load Data</h1>
<table>
  <tr>
    <th>Bullet</th>
    <th>Powder</th>
    <th>Caliber</th>
  </tr>

  <% @articles.each do |article| %>
   <tr>
     <td><%= article.bullet %></td>
     <td><%= article.powder %></td>
     <td><%= article.calibertitle %></td>
     <td><%= link_to '[View]', article_path(article) %></td>
     <td><%= link_to '[Edit]', edit_article_path(article) %></td>
     <td><%= link_to '[Delete]', article_path(article),
             method: :delete,
             data: { confirm: 'Are you sure?' } %></td>
   </tr>
  <% end %>
<%= link_to 'Back', controller: 'welcome' %>
<p>
</table>

articles_controller.rb

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

/models/article.rb

class Article < ApplicationRecord

  validates :calibertitle, presence: true,
                           length: { minimum: 3 }

end

1 个答案:

答案 0 :(得分:1)

在您的控制器中,假设您有一个名为calibertitle的列:

def index
  @articles = Article.all.order(:calibertitle)
end

要在字段中获取具有特定值的文章:Article.where(calibertitle: '308')

您可以在rails控制台中尝试此操作以进行验证。如果需要,您还可以{... 1}进行排序。反向。