【发布时间】:2014-02-28 23:08:06
【问题描述】:
我已经设置了两个可以通过同一个 cmets 表进行注释的模型:
我的 cmets 架构:
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
我的 cmets 控制器:
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
如何向已有的内容添加线程(回复 cmets)?
这是一个讨论线程的博客: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 %>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4