Reputation: 5953
I'm using gem 'ransack' to search records.
The page I'm programming starts with ONLY a dropdown to select @department
.
After that, I want Ransack to search within @department
.
I need to include an additional parameter department=2
with the Ransack search parameters. (It works if I insert that into the browser URL).
Browser URL after I type in department=2
http://localhost:5000/departments/costfuture?department=2&utf8=%E2%9C%93&q%5Bid_eq%5D=&q%5Bproject_year_eq%5D=&q%5Boriginal_year_eq%5D=&q%5Bclient_id_eq%5D=43&q%5Blocation_name_cont%5D=&q%5Bproject_name_cont%5D=&q%5Bcoststatus_id_in%5D%5B%5D=&q%5Bcoststatus_id_not_in%5D%5B%5D=&q%5Brebudget_true%5D=0&q%5Bnew_true%5D=0&q%5Bconstruction_true%5D=0&q%5Bmaintenance_true%5D=0&commit=Search
This is the controller:
def costfuture
@departments = current_user.contact.departments
if params[:department]
@department = Department.find(params[:department])
@search = @department.costprojects.future.search(params[:q])
@costprojects = @search.result.order(:department_priority)
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @departments }
end
end
I tried this in the view:
<%= search_form_for @search, url: departments_costfuture_path(:department => @department.id) do |f| %>
But, the resulting URL is missing the department=2
.
Upvotes: 3
Views: 3615
Reputation: 532
I ended up using hidden_field_tag
inside search_form_for
.
<%= search_form_for @search, url: departments_costfuture_path do |f| %>
<%= hidden_field_tag :department, @department.id %>
<%= f.search_field :last_name_or_first_name_cont %>
<% end %>
Then params[:department]
and params[:search]
will be accessible in the controller.
Upvotes: 4
Reputation: 6072
If you want to pass the department
option through to Ransack, you can do this with a hidden field within your search_form_for
:
<%= search_form_for @search, url: departments_costfuture_path do |f| %>
<%= f.hidden_field :department_eq, value: @department.id %>
<%# Other form code here %>
<% end %>
But if you want to search a particular department, then it's better to use Rails routes for that. You can generate URLs like /departments/2/costfuture
by modifying config/routes.rb
:
resources :departments do
get 'costfutures', on: :member
end
Now you can use the resulting URL helper to generate links that will set params[:id]
, and you can use that to retrieve @department
.
Upvotes: 3