Gem Ransack Doesn't Return Any Results When Searched with Full Name

Gem Ransack doesn't return any results when searched with full name

You have to use a Ransacker. Add this in your User model:

ransacker :full_name do |parent|
Arel::Nodes::InfixOperation.new('||',
parent.table[:first_name], parent.table[:last_name])
end

You can check the Ransack GitHub wiki to more examples.

Why Ransack doesn't show any search results

Your code should say Task.ransack(name_cont: params[:q][:name]) because your params look like this: {"q"=>{"name"=>"TT"} }.

But, you are using the same action, index to render the intial page (when the user lands on it) and also after Search is pressed. When the page renders first, i.e http://localhost/tasks, q parameter does not exist and writing params[:q][:name] will obviously fail because params[:q] is nil.

Ideally, you should keep index to render the search form and have another action for search.

But, if you want to keep everything as is you could write it as follows:

Assuming you have a TasksController:

class TasksController < ApplicationController
def index
@query = Task.ransack(params[:q])
@tasks = @query.result
end
end

And the search form is on /tasks:

<%= search_form_for @query do |f| %>
<%= f.label :name, "Search for" %>
<%= f.search_field :name_cont, placeholder: "Mission Name" %>
<%= f.select :status_eq, Task.statuses.map { |key, value| [key.titleize, value] }, prompt: 'Choose Status' %>
<%= f.submit %>
<% end %>
....

You see I added name_cont as the search field. You could add more, i.e status_eq, and all will be sent to the server in params[:q] when you press Search.

Pay attention to the logs to see how q looks like and what query is performed in Tasks.

Task Load (0.9ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."name" ILIKE '%test%'

Rails app datetime search using Ransack gem

If you're receiving the datetime in string format from parameters and directly passing it to ransack, then you should convert that string to 24-hour format string (db format can also be used) first and then pass it to ransack.

For example

query_value = Time.zone.parse(params[:created_at_filter]).to_s(:db)
Person.ransack(created_at_eq: query_value)

In form sorting using ransack gem not working

In your controller you missed the line

@properties = @q.result(:distinct => true)

which should be after

@q = Property.search(params[:q])


Related Topics



Leave a reply



Submit