11

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

4

3 回答 3

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'


# 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到任何模型。在呈现评论表单时,您只需在本地哈希中传递可评论对象,并且相同的评论控制器/视图代码应该可以工作。

于 2010-09-18T22:19:40.203 回答
7

acts_as_commentable仅向您公开一个 Comment 模型并处理该模型和您的可评论模型之间的管道。它没有给你任何控制器或视图。您有责任决定如何实现应用程序的这一部分。

不过,这很简单。例如...

# 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

当您转到/posts/1/comments现在时,您会看到特定帖子的评论。

于 2010-09-18T13:25:31.593 回答
2

我认为向任何模型添加注释的最佳方法是在 ApplicationController.rb 文件中创建一个名为 comment 的方法,如下所示。

def comment 
  # Extracts the name of the class
  klass = self.class.to_s[/\A(\w+)sController\Z/,1] 
  # Evaluates the class and gets the current object of that class
  @comentable_class = eval "#{klass}.find(params[:id])"
  # Creates a comment using the data of the form
  comment = Comment.new(params[:comment])
  # Adds the comment to that instance of the class
  @comentable_class.add_comment(comment)

  flash[:notice] = "Your comment has been added!"
  redirect_to :action => "show", :id => params[:id] 
end    

然后只需创建一些部分 _comment.rb 以在您想要的任何模型中使用它

<%= form_tag :action => "comment", :id => Your_model_goes_here %>
  <p><label for="comment_title">Title</label><br/>
  <%= text_field 'comment', 'title' %></p>
  <%= text_area "comment", "comment", :rows => 5, :cols => 50 %> <br />
  <%= submit_tag "Comment!.." %>
</form>

我希望它对某人有用...

于 2011-09-15T19:39:26.210 回答