Search code examples
ruby-on-railsnested-attributesransack

Access attributes of associated models in Ransack


I have a dashboard that shows results fetched from users and nannies model.

In my user.rb, I have

User has_many :nannies

The nanny.rb has

Nanny belongs_to :user

User has some basic attributes (name, email, phone etc) Nanny has other attributes (gender, hours, days etc) Right now, I have these lines to implement Ransack and fetch users according to filters. The index method of the controller is

@users = User.ransack(params[:q])
@people = @users.result

I can filter out the results based on attributes from Nanny. The filter form in the view is like this

<%= search_form_for @users do |f| %>
  <%= f.label :firstname_cont %>
  <%= f.search_field :firstname_cont %> 

  <%= f.label :lastname_cont %>
  <%= f.search_field :lastname_cont %>

  <%= f.label :role_eq %>
  <%= f.search_field :role_eq %>

  <%= f.label :nannies_gender_cont %>
  <%= f.search_field :nannies_gender_cont %>

  <%= f.label :nannies_hours_eq %>
  <%= f.search_field :nannies_hours_eq %>

 <%= f.submit %>
<% end %>

The results are displayed like this

    <% @people.each do |test| %>
      <%= test.id %>
      <%= test.firstname %>
      <%= test.email %>
      <%= test.hours %>
    <% end %>

I am getting an error 'undefined method hours for User' (which obviously belongs to the Nanny model).

I need to be able to achieve the following

  1. Load all Users and its associated Nannies

  2. Run Ransack and filter out the results

  3. Display all attributes from all associated models in the view

Would really appreciate any guidance/correction in this issue.


Solution

  • Assuming your question is how to fix undefined method hours for User:

    The following solution is not really a Ransack "thing", but more just a Rails "thing":

    <% @people.each do |test| %>
      <%= test.id %>
      <%= test.firstname %>
      <%= test.email %>
      <% test.nannies.each do |nanny| %>
        <%= nanny.hours %>
      <% end %>
    <% end %>
    
    • You need to loop through each nanny that belongs to test (of which is a User record), and from there only when you can access hours value for each nanny