I am trying to do search functionality for my Rails MVC learning. I am adding title , description and category name as filter columns. And checking each parameter id defined in my model class using self method. But when loading view for first time, Its getting result as expected. But with parameters, my article object is not getting any response in rails view,
My controller articles_controller.rb method,
def search
@articles = Article.all
if(params.has_key?(:title) || params.has_key?(:description) || params.has_key?(:name))
@articles = Article.search_artcat(:params)
end
#render plain: params[:article][:title]
end
My article.rb model file has,
def self.search_artcat(params)
conditions = String.new
wheres = Array.new
if params.has_key?(:title)
conditions << " AND " unless conditions.length == 0
conditions << "title = ?"
wheres << params[:title]
end
if params.has_key?(:description)
conditions << " AND " unless conditions.length == 0
conditions << "description = ?"
wheres << params[:description]
end
wheres.insert(0, conditions)
@article = Article.joins(:categories).where(wheres)
end
And my view file search.html.erb,
<h1>Search article</h1>
<%= form_with scope: :article, url: search_path ,method: :get, data: { turbo: false} do |f| %>
<table>
<td>
<%= f.label :title %><br/>
<%= f.collection_select(:title, Article.all, :title, :title,{ prompt: "Select Title "}, { multiple: false}) %>
</td>
<td>
<%= f.label :description %>
<%= f.collection_select(:description, Article.all, :description, :description,{ prompt: "Select Description "}, { multiple: false}) %>
</td>
<td>
<%= f.label :name %>
<%= f.collection_select(:name, Category.all, :name, :name,{ prompt: "Select Category "}, { multiple: false}) %>
</td>
<td>
<%= f.submit %>
</td>
<% end %>
<h3> Search Result </h3>
<% unless @articles.blank? %>
<table>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.description %></td>
<% article.categories.each do |cat|%>
<td> <%= cat.name %></td>
<% end %>
</tr>
<% end %>
</table>
<% end %>
routes.rb file has
resources :articles
resources :categories, except: [:destroy]
get 'search', to: 'articles#search'
And Article has many to many association through ArticleCategory
Can anyone one please guide to resolve or suggest any method to make implementation correctly?