简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM