Rails Activerecord table includes table

I have four tables:

argument with fields

  • ID

comments from

  • ID
  • comment_id
  • argument_id
  • user_id

of users

  • ID

nicknames with

  • ID
  • proposal_id
  • user_id
  • name

each argument has many comments,

each comment belongs to the user,

each user has a specific alias in the argument.

When I get argument comments from the database, I would also like to include the aliases of each author.

The answer is about an ActiveRecord request that I don't know how to write .

I tried using

@argument.comments.includes(:user => :nicknames)

but it doesn't work, and when I get the nickname through nickname = @ argument.nicknames.find_by_user_id (comment.user.id) it fulfills the request ...

[1m[36mNickname Load (0.6ms)[0m  [1mSELECT "nicknames".* FROM "nicknames" WHERE "nicknames"."argument_id" = 59 AND "nicknames"."user_id" = 9 LIMIT 1[0m

any suggestion?

+5
3

, loaded?.

, , , finder ActiveRecord:: Relation. , , , , . , , . ( , , ):

c = Canteen.first
Canteen Load (0.2ms)  SELECT "canteens".* FROM "canteens" LIMIT 1
=> #<Canteen id: 1, name: "Really good place", created_at: "2012-12-13 00:04:11", updated_at: "2012-12-13 00:04:11">

c.meals.loaded?
=> false

c.meals.find {|m| m.id == 3}
  Meal Load (0.2ms)  SELECT "meals".* FROM "meals" WHERE "meals"."canteen_id" = 1
=> #<Meal id: 3, canteen_id: 1, name: "Banana Pie", price: #<BigDecimal:7fcb6784fa78,'0.499E1',18(45)>, created_at: "2012-12-13 00:37:41", updated_at: "2012-12-13 00:37:41">

, ActiveRecord . , ActiveRecord to_a , , . , .

, .

c = Canteen.includes(:meals).first
  Canteen Load (0.2ms)  SELECT "canteens".* FROM "canteens" LIMIT 1
  Meal Load (0.2ms)  SELECT "meals".* FROM "meals" WHERE "meals"."canteen_id" IN (1)
=> #<Canteen id: 1, name: "Really good place", created_at: "2012-12-13 00:04:11", updated_at: "2012-12-13 00:04:11">

c.meals.loaded?
=> true

c.meals.find {|m| m.id == 3}
=> #<Meal id: 3, canteen_id: 1, name: "Banana Pie", price: #<BigDecimal:7fcb68b596f0,'0.499E1',18(45)>, created_at: "2012-12-13 00:37:41", updated_at: "2012-12-13 00:37:41">

, . .

, , ActiveRecord :

c.meals.loaded?
=> true

c.meals.find(1)
  Meal Load (0.1ms)  SELECT "meals".* FROM "meals" WHERE "meals"."canteen_id" = 1 AND "meals"."id" = ? LIMIT 1  [["id", 1]]
=> #<Meal id: 1, canteen_id: 1, name: "Enchiladas", price: #<BigDecimal:7fcb6584ce88,'0.699E1',18(45)>, created_at: "2012-12-13 00:04:40", updated_at: "2012-12-13 00:04:40">

SELECT "meals".* FROM "meals" WHERE "meals"."canteen_id" = 1 AND "meals"."id" = 3
=> [#<Meal id: 3, canteen_id: 1, name: "Banana Pie", price: #<BigDecimal:7fcb68b808e0,'0.499E1',18(45)>, created_at: "2012-12-13 00:37:41", updated_at: "2012-12-13 00:37:41">]
+2

- :

@argument.includes(:comments => [{ :user => :nicknames }])

, ...

0

You can try something like this to include more than one table

 User.find(:all, :include => Room.find(:all,:include => :review))
0
source

All Articles