您好,登錄后才能下訂單哦!
在Rails中實(shí)現(xiàn)搜索功能可以通過以下步驟實(shí)現(xiàn):
# app/models/post.rb
class Post < ApplicationRecord
def self.search(query)
where("title LIKE ?", "%#{query}%")
end
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
if params[:query].present?
@posts = Post.search(params[:query])
else
@posts = Post.all
end
end
end
<!-- app/views/posts/index.html.erb -->
<%= form_tag(posts_path, method: "get") do %>
<%= text_field_tag :query, params[:query], placeholder: "Search posts..." %>
<%= submit_tag "Search" %>
<% end %>
<!-- app/views/posts/index.html.erb -->
<% @posts.each do |post| %>
<h2><%= post.title %></h2>
<p><%= post.content %></p>
<% end %>
通過以上步驟,就可以在Rails應(yīng)用中實(shí)現(xiàn)搜索功能。用戶可以在搜索表單中輸入關(guān)鍵詞,點(diǎn)擊搜索按鈕后會(huì)顯示符合搜索條件的結(jié)果。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。