簡體   English   中英

Rails Join Model選擇聯合列

[英]Rails Join Model select joint columns

我有以下三個模型加入關系

class Book < ActiveRecord::Base
  has_many :contributions, :dependent => :destroy
  has_many :contributors, :through => :contributions
end

class Contributor < ActiveRecord::Base
  has_many :contributions, :dependent => :destroy
  has_many :books, :through => :contributions do
    def this_is_my_contribution(book, join_attrs) 
      Contribution.with_scope(:create => join_attrs) {self << book}
    end
  end
 end

class Contribution < ActiveRecord::Base
  belongs_to :book
  belongs_to :contributor
end

然后在將記錄插入Contribution連接模型后,我決定對此模型進行查詢以檢索所有書籍和貢獻者名稱作為結果查詢,如下面的SQL等效項

SELECT Contributions.*, Contributors.name, Books.name from Contributions 
INNER JOIN Contributors ON Contributors.id = Contributions.contributors_id 
INNER JOIN Books ON Books.id = Contributions.books_id

但在irb控制台中,當我寫這篇文章時,

Contribution.joins(:contributor, :book).select("contributors.name, books.name,
  contributions.*")   

我得到以下輸出

 Contribution Load (0.8ms)  SELECT contributors.name, books.name, contributions.* FROM
 "contributions" INNER JOIN "contributors" ON "contributors"."id" =
 "contributions"."contributor_id" INNER 
 JOIN "books" ON "books"."id" = "contributions"."book_id"                                                                                                                                          
 => #<ActiveRecord::Relation [#<Contribution id: 1, book_id: 1, contributor_id: 1, role: 
 "author", created_at: "2014-04-04 00:19:15", updated_at: "2014-04-04 00:19:15">, #
 <Contribution id: 2, book_id: 2, contributor_id: 2, role: "Author", created_at: "2014-
 04-05 06:20:34", updated_at: "2014-04-05 06:20:34">]>   

我沒有根據內部聯接外鍵獲得任何書名和貢獻者的名字。

當我真正想要的時候,我無法理解RAILS SQL語句是如何出錯的。

我完全理解的是什么?

Rails模型與與之關聯的表映射,因此在查詢此模型后,它返回模型對象,在這種情況下是沒有其他模型屬性的Contribution模型,以實現您希望將編寫查詢所需的內容

contributions = Contribution.joins(:contributor, :book).select("contributors.name
  as c_name, books.name as b_name, contributions.*")

返回的結果將是Contributions數組,並且可以通過屬性b_name獲得結果的書名

contributions.last.b_name

注意:根據您將如何使用查詢結果,您必須在joins之間進行選擇, includes您可以閱讀此處

是的,在查詢的響應中你不會看到任何書名,但是如果你得到[0] .book.name,你會看到書的名字。 它在顯示的結果中不可見,但您只需訪問它即可獲得它。

正如sat所說,你可以使用include,這樣當你訪問book表時它就不會進行額外的查詢,但是在join中它會為每次訪問book表進行額外的DB調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM