簡體   English   中英

在Ruby on Rails中處理評論

[英]Dealing with Comments in Ruby on Rails

目前,我正在制作一個簡單的類似博客的應用程序,用戶可以在其中發布信息,其他幾個用戶可以對此發表評論。

有沒有一種方法可以使多態屬性屬於多個模型?

例如,

評論將始終具有作者(用戶模型)。但是,評論可以屬於許多其他模型(帖子,期刊,文章等)

因此,對於(帖子,期刊,文章)模型,多態關聯是最好的。 但是,對於作者(或用戶關系)而言,多態無法正常工作,因為一次只能屬於一個多態。

有沒有更好的辦法解決這個問題?

編輯:什么是這樣做的利弊:

class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :commentable, :polymorphic => true
end

EDIT2:使用上述解決方案,是否有更優雅的方法

def create
    @comment = @commentable.comments.new(params[:comment])
    @comment.user_id = current_user.id

    if @comment.save
        flash[:success] = 'Comment created'
        redirect_to @commentable
    else
        flash[:error] = 'Comment not created - is body empty?'
        redirect_to @commentable
    end
end

無需在控制器中手動保存user_id?

    @comment.user_id = current_user.id

您既可以具有User關系,也可以具有表示與之關聯的模型的多態關系。 例如:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :document, polymorphic: true
end

class Post < ActiveRecord::Base
  has_many :comments, as: :document
end

class Journal < ActiveRecord::Base
  has_many :comments, as: :document
end

class Article < ActiveRecord::Base
  has_many :comments, as: :document
end

class User < ActiveRecord::Base
  has_many :comments
end

現在,你可以調用comment.user來獲取User模型誰創造了意見和人comment.document拿到PostJournalArticle的評論與相關聯。

暫無
暫無

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

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