Search code examples
ruby-on-railsacts-as-commentable

Rails: Implementing an acts_as_commentable_with_threading form


I'm trying to create a form that utilizes the acts_as_commentable_with_threading gem. Although I have working code, it's got a couple of kinks. My main concern is that I've had to make a hidden_field for the commentable object's id. I suspect there's a way to bypass this on account of the gem's build-in method, build_from. If you know how to do that, please share. At the moment, here's what my code looks like:

In my Impressions controller I have:

@impression = @book.impressions.find_by_user_id(user)
@new_comment = Comment.build_from( @impression, current_user.id, "" )

In my view, I have:

<%= form_for @new_comment, :remote => true do |f| %>
  <%= f.text_area :body %>
  <%= f.hidden_field :commentable_id, :value => @impression.id %>
  <%= f.submit 'Submit' %>
<% end %>

And in the Comments controller I have:

def create
  @comment = Comment.build_from( Userimpression.find(params[:comment][:commentable_id]), current_user.id, params[:comment][:body] )
  @comment.save
end

In the Comments model:

def self.build_from(obj, user_id, comment)
  c = self.new
  c.commentable_id = obj.id
  c.commentable_type = obj.class.base_class.name
  c.body = comment
  c.user_id = user_id
  c
end

Solution

  • I know this is an old answer, but a good tutorial that covers a few aspects of this gem, is: http://twocentstudios.com/blog/2012/11/15/simple-ajax-comments-with-rails/

    It doesn't help you with the children handling, but its easy to figure it out.