MH Sagar
MH Sagar

Reputation: 136

Query to get all data from associated model on rails

I have one User model and StudentProfile model associations are

class User < ApplicationRecord
  has_one :student_profile 
end

class StudentProfile < ApplicationRecord
  belongs_to :user 
end

I want to render all fields of both table. SQL command for the action is

select * from users join student_profiles on student_profiles.user_id = users.id

But

User.joins(:student_profile)

shows only the fields of User table. I need to all info from both table in json fomat as I'll use this url for an ajax call.

Is there any way to realise this sql in active record query?

select * from users join student_profiles on student_profiles.user_id = users.id

Upvotes: 0

Views: 642

Answers (1)

Mosaaleb
Mosaaleb

Reputation: 1089

You can use select to select the fields that you want:

User.joins(:student_profile).select('users.*, student_profiles.*')

* is for selecting all fields

Or Choosing specific fields from student_profiles table:

User
  .joins(:student_profile)
  .select('users.*, student_profiles.first_name, student_profiles.last_name')

But I would suggest reading about active model serializers since you dealing with JSON.

Upvotes: 1

Related Questions