Gem Ransack returns no results when searching with full name
I am using Ransack with Rails 3.
My views:
<%= search_form_for @search do |f| %>
<%= f.text_field :first_name_or_last_name_or_company_cont, :style => 'width:150px;padding-top:6px;' %><p class="button">
<%= f.submit "Search by name or company" %></p>
<% end %>
My circuit:
create_table "users", :force => true do |t|
t.string "first_name",
t.string "last_name"
in user model I have:
def full_name
"#{self.first_name} #{self.last_name}"
end
Working with the console.
If I have a user with first_name = "Foo"
, last_name = "Bar"
when I search for one of them, I get the results as expected.
When I search with full_name = "Foo Bar"
, I don't get any results.
I tried to change my textbox for Ransack to:
<%= f.text_field :first_name_or_last_name_or_company_or_full_name_cont
I get first_name_or_last_name_or_company_or_full_name_cont is undefined
is there a quick way to solve this without adding another column for full_name in my users table?
also:
7: def index
8: search_params = params[:q]
=> 9: binding.pry
[1] pry(#<UsersController>)> search_params
=> {"first_name_or_last_name_or_company_cont"=>"Foo Bar"}
I think I can split the key value here to only search for the first name.
source to share
You must use Ransacker
. Add this to your model User
:
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 for a few examples.
source to share
Add the following code to your model:
ransacker :full_name do |parent|
Arel::Nodes::InfixOperation.new('||',
Arel::Nodes::InfixOperation.new('||',
parent.table[:first_name], Arel::Nodes.build_quoted(' ')
),
parent.table[:last_name]
)
end
... and in your opinion:
<%= f.label :full_name %><br>
<%= f.search_field :full_name_cont %>
The ransacker part was taken from the Ransack wiki .
Tested on Rails 4.2 with PostgreSQL.
source to share