我已经建立了两个模型,它们可以通过相同的注释表进行注释:
我的评论模式:
create_table "comments", force: true do |t|
t.text "body"
t.integer "commentable_id"
t.string "commentable_type"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end我的评论模式:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
acts_as_votable
end我的电影模型
class Movie < ActiveRecord::Base
belongs_to :user
has_many :comments, as: :commentable
end我的书模型:
class Book < ActiveRecord::Base
belongs_to :user
has_many :comments, as: :commentable
end我的评论负责人:
def index
@commentable = find_commentable
@comments = @commentable.comments
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user = current_user
if @comment.save
flash[:notice] = "Successfully created comment."
redirect_to @commentable
else
render :action => 'new'
end
end
def upvote_movie
@movie = Movie.find(params[:movie_id])
@comment = @movie.comments.find(params[:id])
@comment.liked_by current_user
respond_to do |format|
format.html {redirect_to :back}
end
end
def upvote_book
@book = Book.find(params[:book_id])
@comment = @book.comments.find(params[:id])
@comment.liked_by current_user
respond_to do |format|
format.html {redirect_to :back}
end
end
private
def find_commentable
params[:commentable_type].constantize.find(params[:commentable_id])
end
end如何将线程(回复评论)添加到我已经拥有的内容中?
下面是一个关于线程的博客:http://www.davychiu.com/blog/threaded-comments-in-ruby-on-rails.html
我只是不知道怎么把这两者结合起来。
以下是我在电影放映中看到的内容:
<%= render partial: "comments/form", locals: { commentable: @movie } %>
<% @comments.each do |comment| %>
<hr>
<p>
<strong><%= link_to comment.user.username, user_path(comment.user), :class => "user" %>
</strong> <a><%= "(#{time_ago_in_words(comment.created_at)} ago)" %></a>
</p>
<p>
<%= simple_format(auto_link(comment.body, :html => { :target => '_blank' } )) %>
<% end %>下面是我的评论表格:
<%= form_for [commentable, Comment.new] do |f| %>
<%= hidden_field_tag :commentable_type, commentable.class.to_s %>
<%= hidden_field_tag :commentable_id, commentable.id %>
<p>
<%= f.text_area :body %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>发布于 2014-02-28 13:44:52
我浏览了你提到的那篇文章,发现那里的解决方案非常有限。
本文的基本思想是将评论本身设置为可评论。因此,嵌套注释实际上不是帖子的注释,而是父注释的注释。
缺点是明显和不可接受的:
posts.comments.size不再是正确的。实际上,一个简单的解决方案可以解决这个问题:
reply_to,引用其他注释的id。reply_to id回复了一个注释,则添加它。reply_to null的所有注释的列表。nested_level字段,从前端进入。如果嵌套限制为3,则不允许评论回复nest级别为3的注释。添加:演示助手,用于递归呈现
def render_replied_comments(comment)
if comment.has_reply
comments.replies.each do |reply|
render partial: 'comment', locals: {comment: reply}
render_replied_comment(reply)
end
end
end
# View
@post.top_level_comments.each do |comment|
render partial: 'comment', locals: {comment: comment}
end发布于 2014-02-28 13:43:52
您将向注释模型添加一个parent_id,该模型是一个自引用关系。因此父注释的parent_id为零,所有子注释都有父注释的parent_id。你实际上是在建造一棵树。
祖先宝石是理想的或滚动自己的,良好的学习经验。
https://stackoverflow.com/questions/22096134
复制相似问题