Rails 的 joins 中 select 的欄位不會在 console 中顯示

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
1.14K   0  
·
2018/07/16
·
1 mins read


寫網頁,少不了要用上 joins,在 rails 中,沒指明,joins 就是 inner joins,也就是交集,這個很好用,特別是配合上 select,更可以把指定的兩個 tables 中的欄位帶入變數中。 比較討厭的是,如果各位跟我一樣,喜歡用 rails c 中驗證 SQL,conole 並不會顯示出來,舉例來說:

test = User.joins(:blog).select('user.id, user.name, blog.title')

這時用 console 執行後,卻會顯示如此:

irb(main):xx:0> User Load (0.9ms)  SELECT users.id,users.name,blog.title FROM "users" INNER JOIN "blog" ON "blog"."user_id" = "users"."id"
=> #<ActiveRecord::Relation [#<User id: 1, name: "Andy">]>

很奇怪的,明明有指定 blog.title 為什麼怎麼試就是沒有顯示出來?

其實是有的,只是 rails console 沒顯示,我也不知道為什麼,照道理應該要,我想任何平台總有些不足的,來在 rails c 中驗證一下:

irb(main):xx:0> test.first.title
=> "第一筆 blog 的 title"

確定有,只是 console 沒顯示! 

還有一個常用的,就是當兩個 joins 的 table 都有一樣的名稱時,怎麼指定?就用個 as:

User.joins(:blog).select('user.id, user.name, blog.title, blog.id as blog_id')

很簡單吧,如果要把所有的 columns 都用 select 帶入,就是:user.*,只是,真有必要嗎?有時太懶就要都用一些記憶體,一笑!


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

This article is part of:
Categories:
Tags:
Total: 299 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.