Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
Sayuj Avatar asked Mar 03 '26 09:03

Sayuj


2 Answers

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.

like image 161
apneadiving Avatar answered Mar 05 '26 03:03

apneadiving


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
like image 38
mliebelt Avatar answered Mar 05 '26 04:03

mliebelt