Sayuj
Sayuj

Reputation: 7622

Ruby on rails activerecord joins - select fields from multiple tables

models:

#StatusMessage model
class StatusMessage < ActiveRecord::Base
  belongs_to :users
  default_scope :order => "created_at DESC"
end


#User Model
class User < ActiveRecord::Base
  has_many :status_messages 
end

In controller I want to join these two tables and get fields from both table. for example I want email field from User and status field from StatusMessage. When I use :

@status = User.joins(:status_messages)

Or

@status = User.includes(:status_messages)

It gives me only the user table data.

How can I implement this requirement?

Upvotes: 3

Views: 12934

Answers (3)

Taimoor Changaiz
Taimoor Changaiz

Reputation: 10684

When you use @status = User.includes(:status_messages) then rails eagerley loads the data of all the tables.

My point is when you use this User.includes(:status_messages) it will loads the data of status_messages also but shows only users table data then if you want first user status_messages then you have to @user.first.status_messages

Upvotes: 1

mliebelt
mliebelt

Reputation: 15525

First of all, I don't think it is possible (and reasonable) what you want to do. The reason for that is that the relation between User and StatusMessage is 1:n, that means that each user could have 0 to n status messages. How should these multitudes of attributes be included in your user model?

I think that the method joints in class ActiceRecord has a different meaning, it is part of the query interface. See the question LEFT OUTER joins in Rails 3

There are similar questions on the net, here is what I have found that matches most:

  • Ruby on Rails: How to join two tables: Includes (translated for your example) in the user a primary_status_message, which is then materialized in the query for the user. But it is held in one attribute, and to access the attributes of the status_message, you have to do something like that: @user.primary_status_message.status

Upvotes: 2

apneadiving
apneadiving

Reputation: 115511

You need to use includes here. It preloads data so you won't have another SQL query when you do @user.status_messages.

And yes you can't really see the effect: you need to check your logs.

Upvotes: 7

Related Questions