Rails 5.1.2 ransack includes how to add deep associoations?

Viewed 435

I have following models and i wish search Order model with criteria related to models Department Supplier

Question is how to includes other models Supplier and Department in this code

@q = Order.ransack(params[:q])
@objednavky = @q.result.includes(:user,:food).page(params[:page])

Definitions of models

class Supplier < ApplicationRecord
  has_many :food
end

class User < ApplicationRecord
  belongs_to :department
  has_many :orders
end

class Department < ApplicationRecord
  has_many :users
end

class Food < ApplicationRecord
  belongs_to :supplier
  has_many :order 
end

class Order < ApplicationRecord
  belongs_to :user
  belongs_to :food
end
1 Answers

I had a similar issue and could not find the answer anywhere. Eventually figured out the following:

  private def search_includes
    [
      user: :department,
      food: :supplier
    ]
  end
  @objednavky = @q.result.includes(search_includes).page(params[:page])

If the association is deeper I believe you can nest by doing something like:

  private def search_includes
    [
      user: :department,
      food: [supplier: :another_assoc]
    ]
  end

Hope this helps others and apologies if this is not what you are asking.

Related