rails 4充当可评论的回复链接

时间:2014-03-13 23:04:58

标签: ruby-on-rails ruby

我正在使用acts_as_commentable来嵌套post-comments- reply。有没有人可以给我很好的例子,特别是在评论控制器和发布展示视图。我感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是model / 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),在comment_controller中创建#create:

@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

这就是全部,跳吧有帮助