简体   繁体   English

Rails:加入“ has_one”和“ belongs_to”协会

[英]Rails: joining the 'has_one' and 'belongs_to' association

I have two models: 我有两个模型:

class User < ActiveRecord::Base
 has_one :user_profile
end

class UserProfile < ActiveRecord::Base
  belongs_to :user
end

a User has one UserProfile , and a UserProfile belongs to a User 一个User有一个UserProfile ,一个UserProfile属于一个User

The tables structure: 表结构:

User 用户

id : integer name : string email : string id:整数名称:字符串电子邮件:字符串

UserProfile 用户资料

id : integer user_id : integer bio : string blog_url : string id:整数user_id:整数bio:字符串blog_url:字符串

Using rails console, I try to get the information of a User by joining both tables: 使用rails console,我尝试通过连接两个表来获取用户的信息:

User.joins(:user_profile).includes(:user_profile).where(user_profiles: {user_id: 1})

The result on the console screen shows me only the User table, the UserProfile table doesn't show up. 控制台屏幕上的结果仅显示User表,而UserProfile表未显示。

 => [#<User id: 1, name: "Alan", email:"alan@example.com">]

The SQL statement that appeared on the console screen (the SELECT "users"."id" bla bla...) seems right, since when I copy and paste it to SQLite browser and execute the command, it shows me the result as I expected. 出现在控制台屏幕上的SQL语句(SELECT“ users”。“ id” bla bla ...)看起来是正确的,因为当我将其复制并粘贴到SQLite浏览器并执行命令时,它向我显示结果预期。

|id| name | email            | id | user_id | bio         | blog_url         | 
------------------------------------------------------------------------------
|1 | Alan | alan@example.com | 1  | 1       | lorem ipsum | alan.example.com |

So I found two different results here. 所以我在这里发现了两个不同的结果。

What might cause these tables not joining on my console? 是什么原因导致这些表未加入控制台?

what you see in console: 您在控制台中看到的内容:

=> [#<User id: 1, name: "Alan", email:"alan@example.com">]

is a string representation of a User object, default representation does not include loaded associations(imagine you had million other objects associated with that user - you wouldn't be able to get the thing rendered at all) 是User对象的字符串表示形式 ,默认表示形式不包括已加载的关联(假设您有数百万个与该用户关联的其他对象-您将无法获得所有呈现的内容)

to access user profile from user object you have a convenient #user_profile method: 要从用户对象访问用户个人资料,您可以使用便捷的#user_profile方法:

p user.user_profile

to be sure that you're actually fetching this thing from memory and not revisiting database(which is what you are using .include() for) you can tail log/development.log and see that there are no SELECT * FROM user_profiles queries at the time when you access user_profile object 确保您实际上是从内存中获取此内容,而不是重新访问数据库(这是您使用.include()的目的),您可以拖尾log / development.log并查看在以下位置没有SELECT * FROM user_profiles查询访问user_profile对象的时间

also you don't need both .joins() and .includes() . 您也不需要.joins().includes() usually .includes() does all you need. 通常.includes()做了所有你需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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