我试图在应用程序中执行数据库搜索,但是,我一直无法使搜索正常工作。Ruby on Rails中的数据库查询
在索引页面中,我可以选择搜索或显示数据库中的所有项目,但似乎总是调用return all
而不是搜索。如果有人搜索,我想只在搜索完成时显示搜索到的项目。
但是,我遇到了一些问题。
articles_controller.rb:
class ArticlesController < ApplicationController
def index
if params[:id]
fun = Article.find_by(title: params[:id].search)
else
@articles = Article.all
end
end
def show
@article = Article.find(params[:search])
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(params.require(:article).permit(:title, :text))
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
article.rb:
class Article < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
def self.search(search)
if :search
Article.where('tite LIKE ?', "%#{search}%")
else
Article.all
end
end
end
index.html.erb:
<h1>Listing articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="3"></th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
<%= form_tag articles_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :title => nil %>
</p>
<% end %>
</table>
后端DB:
Started GET "/articles?search=asdfa&commit=Search&utf8=%E2%9C%93" for ::1 at 2016-03-14 15:01:12 -0400
Processing by ArticlesController#index as HTML
Parameters: {"search"=>"asdfa", "commit"=>"Search", "utf8"=>"✓"}
Article Load (0.1ms) SELECT "articles".* FROM "articles"
Rendered articles/index.html.erb within layouts/application (1.4ms)
Completed 200 OK in 19ms (Views: 18.6ms | ActiveRecord: 0.1ms)
最新的错误/不正确调用是:
Started GET "/assets/application.self-3b8dabdc891efe46b9a144b400ad69e37d7e5876bdc39dee783419a69d7ca819.js?body=1" for ::1 at 2016-03-14 15:39:25 -0400
Started GET "/articles?search=asdfa&commit=Search&utf8=%E2%9C%93" for ::1 at 2016-03-14 15:39:40 -0400
Processing by ArticlesController#index as HTML
Parameters: {"search"=>"asdfa", "commit"=>"Search", "utf8"=>"✓"}
Article Load (0.1ms) SELECT "articles".* FROM "articles"
Rendered articles/index.html.erb within layouts/application (1.3ms)
Completed 200 OK in 18ms (Views: 17.2ms | ActiveRecord: 0.1ms)
我究竟在做什么错?我该如何修复/完成这项工作?
当问它有助于想出了一个更明确的标题,不是通用的,不伦不类。标题是吸引那些你希望帮助你的人的注意力,所以准确性很好。 –