您可以使用select选择所需的字段:
我有一个User
模型,并且StudentProfile
个模型关联是>
class User < ApplicationRecord has_one :student_profile end class StudentProfile < ApplicationRecord belongs_to :user end
我想呈现两个表的所有字段。该操作的SQL命令是
select * from users join student_profiles on student_profiles.user_id = users.id
但是
User.joins(:student_profile)
仅显示
User
表的字段。我需要json fomat中的两个表中的所有信息,因为我将使用此url进行ajax调用。
有什么方法可以在活动记录查询中实现此sql吗?
select * from users join student_profiles on student_profiles.user_id = users.id
我有一个User模型,并且StudentProfile模型关联是类User
您可以使用select选择所需的字段:
User.joins(:student_profile).select('users.*, student_profiles.*')
*
用于选择所有字段
或
从student_profiles
表中选择特定字段:User .joins(:student_profile) .select('users.*, student_profiles.first_name, student_profiles.last_name')
但是自您处理JSON以来,我建议阅读有关活动模型序列化程序的信息。
您可以使用select选择所需的字段: