簡體   English   中英

Rails has_one具有多態注釋

[英]Rails has_one with polymorphic comments

我在獲取項目的最后評論時遇到問題,在此特定情況下,我需要對Topic模型進行最后評論。 因為注釋是多態的,所以當我使用:commentable_id作為外鍵時會得到錯誤的結果。

has_one :latest_comment, -> { order(created_at: :desc).limit(1) }, class_name: "Comment", foreign_key: :commentable_id

這是因為,例如,如果我的主題ID為7,然后有人在ID為7的Track上發表評論,Rails會將該Track評論的信息顯示為最新評論。

我遍歷主題時的部分看法:

<% if topic.comments.any? %>
    last reply by <%= link_to topic.latest_comment.user.username, user_path(topic.latest_comment.user) %>
<% else %>
    by <%= link_to topic.user.username, user_path(topic.user_id) %>
<% end %>

我如何在模型中包含諸如where語句之類的內容,因此除了:commentable_id外鍵之外,它還可以獲取commentable_type ==“ topic”?

has_one :latest_comment, -> { order(created_at: :desc).limit(1) }, class_name: "Comment", foreign_key: :commentable_id

where(commentable_type: 'Topic')到上面的現有行中:

has_one :latest_comment, -> { where(commentable_type: 'Topic').order(created_at: :desc).limit(1) }, class_name: "Comment", foreign_key: :commentable_id

更新:

使用has_one :as選項(如此處https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_one所述) ,您還可以執行以下操作:

has_one :latest_comment, -> { order(created_at: :desc).limit(1) }, as: :commentable

暫無
暫無

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

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