我目前在Ruby on Rails中有一個數據庫,但是,我一直在關於如何做其他事情的文檔上遇到問題,而不是列出數據庫中的所有項目。我對整個這種語言還是陌生的,並且希望我不需要這麼多的幫助,但是在這裏它就是這樣。我的相關代碼如下:在Ruby on Rails中搜索字段DB
migrate/(DB name)
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.text :text
t.timestamps null: false
end
end
end
articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
Article.search(params[:id])
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 = Article.where('name LIKE ?', "%#{search}%")
else
@article = Article.all
end
end
end
index.html.rb
<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", :name => nil %>
</p>
<% end %>
</table>
感謝您提前提供任何幫助!
ha,你錯過了「名稱」;) –
真的,剛從OP的問題 –
複製出來,現在我收到了'參數:{「search」=>「asd」,「utf8」=>「✓」 } 文章加載(0.5ms)選擇「文章」。*從後端的「文章」'在前端沒有變化 –