我無法理解如何使用關聯獲取所有相關記錄,而不是關聯ID,如user_id
和comment_id
。 讓我們假設我有三個型號User, Post, Comment, Image
和協會是使用關聯獲取所有相關記錄
User
has_many :posts
has_many :comments
Post
belongs_to :user
has_many :comments
has_many :images
Comment
belongs_to :user
belongs_to :post
Image
belongs_to :post
現在我的用戶的user_id
,並找到用戶爲:
@user = User.find_by_id(params[:id])
@comments = @user.comments
現在我想與他們每個人一個的獲取這些評論他們的帖子的相關記錄。我希望發佈散列,而不是每個評論對應的post_id
。 我想在單個查詢中執行此操作。 如果您有任何想法,請給我建議。
嘗試'@ user.comments.first.post',它會返回一個'POST'實例。謹防這種方法中的[「N + 1查詢」](https://www.sitepoint.com/silver-bullet-n1-problem/)問題得到解決,但這不在您的問題範圍之內。 – mudasobwa
感謝您的考慮@mudasobwa。但我的問題是我想收集評論,而不是post_id,而且每個評論都有相應的帖子記錄。我不想做一個循環來獲取他們每個人的帖子 –