2014-03-13 46 views
0

我正在使用acts_as_commentable嵌套post-comments-回复。有没有人可以给我很好的例子,特别是在评论控制器和发布后视图上。我很感谢你的帮助。rails 4充当评论回复链接

+0

谁投了这个问题,请解释原因。应该给这个新用户带来怀疑。 –

+0

你可以发布一个你的代码示例到目前为止。 –

回答

0

这是模型/ comment.rb

class Comment < ActiveRecord::Base 
    acts_as_nested_set :scope => [:commentable_id, :commentable_type] 

    belongs_to :commentable, :polymorphic => true 

    belongs_to :user 

    def self.build_from(obj, user_id, comment) 
    new \ 
     :commentable => obj, 
     :body  => comment, 
     :user_id  => user_id 
    end 

    def has_children? 
    self.children.any? 
    end 

    scope :find_comments_by_user, lambda { |user| 
    where(:user_id => user.id).order('created_at DESC') 
    } 

    scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id| 
    where(:commentable_type => commentable_str.to_s, :commentable_id => commentable_id).order('created_at DESC') 
    } 

    def self.find_commentable(commentable_str, commentable_id) 
    commentable_str.constantize.find(commentable_id) 
    end 

    def owner?(user) 
    if user.present? 
     return self.user_id == user.id 
    else 
     return false 
    end 
    end 
end 

这是显示在控制器

@comments = @project.comment_threads.order('created_at desc').page(params[:page]) 

@new_comment = Comment.build_from(@project, @user.id, '') 

这是您的形式

= simple_form_for comment, remote: true do |f| 
    = f.input :body, input_html: { rows: '2' }, label: 'Content' 
    = f.input :commentable_id, as: :hidden, value: comment.commentable_id 
    = f.input :commentable_type, as: :hidden, value: comment.commentable_type 
    = f.button :submit, 'Done', class: 'btn btn-primary', disable_with: 'Submitting…' 

根据方法build_from(OBJ,USER_ID,评论),在您的comment_controller#创建:

@user = current_user 
@comment_hash = params[:comment] 
@obj = @comment_hash[:commentable_type].constantize.find(@comment_hash[:commentable_id]) 
@comment = Comment.build_from(@obj, current_user.id, @comment_hash[:body]) 
@comment.save 

就这样,跳它有用