eks*_*atx 11 ruby-on-rails acts-as-commentable
README没有显示如何处理控制器和查看设置此插件的方面.我一直在搜索几个小时,但找不到任何显示如何使用此插件的内容.
eks*_*atx 18
经过更多的搜索,我放弃了寻找教程并想出了这个.如果有人能指出更好/更清洁的方式来做到这一点,请告诉我.否则,这就是我现在正在使用的,以防这将有利于其他任何人.
首先,安装插件 script/plugin install http://github.com/jackdempsey/acts_as_commentable.git -r 2.x
然后,使用生成注释模型和迁移script/generate comment数据库并迁移数据库rake db:migrate
棘手的一点是以多态方式在其他资源下嵌套注释.这是我做的:
# In config/routes.rb
map.resources :comments, :path_prefix => '/:commentable_type/:commentable_id'
Run Code Online (Sandbox Code Playgroud)
# In app/controllers/comments_controller.rb
before_filter :load_commentable
def create
@comment = @commentable.comments.build(params[:comment])
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @commentable }
else
format.html { render :action => 'new' }
end
end
end
protected
def load_commentable
@commentable = params[:commentable_type].camelize.constantize.find(params[:commentable_id])
end
Run Code Online (Sandbox Code Playgroud)
# In app/views/comments/_form.html.erb
<%= form_for(:comment, :url => comments_path(commentable.class.to_s.underscore, commentable.id)) do |f| %>
Run Code Online (Sandbox Code Playgroud)
# In app/views/model_that_allows_comments/show.html.erb
<%= render :partial => 'comments/form', :locals => {:commentable => @model_that_allows_comments} %>
Run Code Online (Sandbox Code Playgroud)
我认为这清楚地显示了相关部分,以便了解正在发生的事情.它可以添加acts_as_commentable到任何模型.您只需在呈现注释表单时传入locals哈希中的可注释对象,并且相同的注释控制器/视图代码应该起作用.
acts_as_commentable只是暴露了一个评论模型,并负责该模型和您的可评论模型之间的管道.它不会为您提供任何控制器或视图.您有责任决定如何实施此部分应用程序.
不过,这很简单.例如...
# in routes.rb
map.resources :posts, :has_many => :comments
# in your comments controller...
class CommentsController < ApplicationController
before_filter :get_post
def get_post
@post = Post.find(params[:post_id])
end
def index
@comments = @post.comments.all # or sorted by date, or paginated, etc.
end
end
# In your haml view...
%h1== Comments for #{@post.title}:
%ul
- comments.each do |comment|
%h3= comment.title
%p= comment.comment
Run Code Online (Sandbox Code Playgroud)
到/posts/1/comments现在为止,你会看到特定帖子的评论.
| 归档时间: |
|
| 查看次数: |
7158 次 |
| 最近记录: |