Rails - 在模型中包含嵌套资源
Rails - Include nested resource in model
我知道如何像这样在控制器渲染中包含嵌套资源:
render :json => @user, :include => {:profile}
我的疑问是:是否可以在模型中做到这一点?
我尝试了很多方法,但没有给我这样的用户和他的个人资料:
{
id: 1,
name: 'John',
profile: {
id: 64,
status: 'active'
}
}
我在我的模型中试过这个:
User.where(id: 1).includes(:profile)
输出为:
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
Profile Load (0.2ms) SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` IN (1)
编辑: 忽略渲染。如果您想在 JSON 输出中包含关联模型,只需调用 [to_json 并将包含作为选项][1].
编辑二: 根据我们的聊天记录,您似乎想要访问对象,而不是 JSON 数据。
使用您的示例用户记录:
users = User.includes(:profile).where("YOUR CONDITIONS")
users.each do |user|
puts user.profile.status #or do something with your loop
end
我知道如何像这样在控制器渲染中包含嵌套资源:
render :json => @user, :include => {:profile}
我的疑问是:是否可以在模型中做到这一点?
我尝试了很多方法,但没有给我这样的用户和他的个人资料:
{
id: 1,
name: 'John',
profile: {
id: 64,
status: 'active'
}
}
我在我的模型中试过这个:
User.where(id: 1).includes(:profile)
输出为:
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
Profile Load (0.2ms) SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` IN (1)
编辑: 忽略渲染。如果您想在 JSON 输出中包含关联模型,只需调用 [to_json 并将包含作为选项][1].
编辑二: 根据我们的聊天记录,您似乎想要访问对象,而不是 JSON 数据。
使用您的示例用户记录:
users = User.includes(:profile).where("YOUR CONDITIONS")
users.each do |user|
puts user.profile.status #or do something with your loop
end