Search code examples
ruby-on-railsruby-on-rails-3.2ransack

Search two models with Ransack Parameters


I have two models: Patient and Facility.

Creating a new patient I have a modal that opens and does a search on the number of patients. Then, I have 4 fields that the usr can fill in and search for a specific patient. Then, when an existing patient is selected some values are passed to a main form. If a patient is not found, the data is passed also to the main form to create a new patient, based on those values...

I'm using Rails 3.2 and Ransack. Here's an example of the parameters returned on one basic search:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"gT8RPTlPiO6Wf3oLcU5+qSzVOZTjBZyX1Y0qNijT5oo=", "q"=>{"nid_cont"=>"2/14", "province_id_eq"=>"2", "district_id_eq"=>"2", "facility_id_eq"=>"146"}}

Then, on patient controller I have this code:

def patient_samples
  @search_patients = Patient.includes(:gender, :province, :district, :facility).search(params[:q])
  @patients = @search_patients.result
  respond_to do |format|
   format.html 
   format.js
   format.json { render json: @patients }
  end
end

This code is run when I open the modal and it returns all existing patients. Then, the user is also able to do the search that will only returns the respective rows.

When I select one of the existing patients, I can get all values from it and all the related models, for example:

patient.facility.printer_type

But when the search doesn't find a patient, I would also like to search the printer_type from the facility that I choose on the search parameters.

What I would like to do is to access one of the q: values, in this case

"facility_id_eq" => "146"

And then do something like:

@facility = Facility.find("146")
@facility.printer_type

But I can't seem to be able to access that value... I've read a lot of similar questions here in Stackoverflow, I've read the gem docs on github, I've tried several things, but haven't been able to do it...

I know it's a simple solution, but I'm blocked on it :(

Can you help me?


Solution

  • You can access that value with

    facility_id = params[:q]['facility_id_eq']
    @facility = Facility.find(facility_id)