I thought it would be difficult to search for multiple columns, but it was easier than I expected, so I thought it would be helpful, so I decided to write it.
I will search for the title and description of the Post model.
class CreatePosts < ActiveRecord::Migration[5.2]
def change
create_table :posts do |t|
t.string :title ⬅️⬅️⬅️⬅️⬅️⬅️ This
t.integer :recommended
t.text :description ⬅️⬅️⬅️⬅️ This
t.references :user, foreign_key: true
t.timestamps
end
add_index :posts, [:user_id, :created_at]
end
end
First, we will change a part of the view. If you want to search only title,
<%= f.search_field :title_cont, placeholder: "Keyword search", class: 'form-control font-awesome' %>
When searching for multiple titles and descriptions
<%= f.search_field :title_or_description_cont, placeholder: "Keyword search", class: 'form-control font-awesome' %>
By comparison, the search target for only title is title_cont, while the search target for multiple titles is title_or_description_cont . Just put or!
Next is the controller. In my case, if only the title is the search target,
def set_search
if logged_in?
@search_word = params[:q][:title_cont] if params[:q]
@q = current_user.feed.page(params[:page]).per(10).ransack(params[:q])
@feed_items = current_user.feed.page(params[:page]).per(10)
@posts = @q.result(distinct: true)
end
end
If you have multiple search targets, you only need to make some changes here as well as the previous view!
@search_word = params[:q][:title_or_description_cont] if params[:q]
Now you can search multiple columns! !! !!
Recommended Posts