NIoSaT
NIoSaT

Reputation: 433

Nested ActiveRecord access

I am trying to access nested ActiveRecord data in my Rails Project.
I want to acces all Devices in all Subnets of a single user
I would like to do something like this:

def index
    @user = User.find(params[:user_id])
    @subnets = @user.subnets.all
    @devices = @subnets.each.devices.order(sort_column+' '+sort_direction).search(params[:search])
    respond_to do |format|
      format.html
      format.csv { send_data Device.to_csv(@devices) }
    end
end

But of cause the @subnet.each.devices part does not work.

Is there a way I could do this without iterating and creating an array, since then I would not be able to use the order function anymore.

Upvotes: 0

Views: 62

Answers (2)

praga2050
praga2050

Reputation: 773

Try this eager_load

 u = User.eager_load({subnets: :devices}).order('devices.updated_by desc').find(1)

This is the query in my log

SELECT "users"."id" AS t0_r0, "users"."username" AS t0_r1, "users"."created_at" AS t0_r2, "users"."updated_at" AS t0_r3, "users"."company_id" AS t0_r4, "users"."location_id" AS t0_r5, "subnets"."id" AS t1_r0, "subnets"."user_id" AS t1_r1, "devices"."id" AS t2_r0, "devices"."subnets_id" AS t2_r1, "devices"."updated_by" AS t2_r2, "devices"."created_by" AS t2_r3 FROM "users" LEFT OUTER JOIN "subnets" ON "subnets"."user_id" = "users"."id" LEFT OUTER JOIN "devices" ON "devices"."subnets_id" = "subnets"."id" WHERE "users"."id" = ? AND "users"."id" = 1 ORDER BY devices.updated_by desc

After this you can get the devices easily :)

Upvotes: 0

Mahmoud Sayed
Mahmoud Sayed

Reputation: 668

Try using joins

@devices = Device.joins(:subnets).where('subnets.user_id = :id', id: @user.id)

Upvotes: 3

Related Questions