ruby-on-rails - 在 Rails 应用程序中实现acts_as_commentable 是否有一种干净的方法?

标签 ruby-on-rails acts-as-commentable

自述文件没有显示如何处理 Controller 和查看设置此插件的方面。我已经搜索了几个小时,但找不到任何显示如何使用此插件的内容。

最佳答案

经过更多的搜索,我放弃了寻找教程并想出了这个。如果有人可以指出更好/更清洁的方法来做到这一点,请告诉我。否则,这就是我现在正在使用的,以防其他人受益。

首先,使用 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'
# 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
# In app/views/comments/_form.html.erb
<%= form_for(:comment, :url => comments_path(commentable.class.to_s.underscore, commentable.id)) do |f| %>
# In app/views/model_that_allows_comments/show.html.erb
<%= render :partial => 'comments/form', :locals => {:commentable => @model_that_allows_comments} %>

我认为这足以清楚地显示相关部分,以了解正在发生的事情。可以添加 acts_as_commentable到任何型号。您只需要在渲染评论表单时传入本地散列中的可评论对象,并且相同的评论 Controller / View 代码应该可以工作。

关于ruby-on-rails - 在 Rails 应用程序中实现acts_as_commentable 是否有一种干净的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3739869/

相关文章:

ruby-on-rails - 获取评论最多的对象

ruby-on-rails - update_all 清除变量中的数组

ruby-on-rails - 为什么我们需要在 rails 中使用命名范围或范围?

ruby-on-rails - Rails 4 + Omniauth + 设计 : Logout link not working

javascript - IE浏览器日期时间问题

ruby-on-rails - 生成的重复 ID 违反了主键约束

ruby-on-rails - rails : solving ambiguity on group using symbols

ruby-on-rails - act_as_commentable 示例?

javascript - rails : acts_as_commentable_with_threading children's comment form not working