With the help of several heroes here yesterday I beat my way into a
working solution to adding comments to one or more models in my
application using acts_as_comentable. Great plugin, but my
implementation is lame. I need enlightenment.
I have users who log in. For several views I want to let them add
comments. Enter act_as_commentable which does just this – it’s
polymorphic, so you just tell your model to act_as_commentable and it
obeys. However…
Say I have a model, view and controller of my reviews of movies, which
I’ll call Reviews. I write a reviews and I want to let my loyal users
add comments.
What does my view (rhtml) look like? The view shows my review, of
course, and perhaps a list of other users’ comments on that review.
But now, Joe wants to comment on my review. Here’s what I have done so
far:
(part of the rhtml of the view, displayed on “show_review” action)
… other stuff on my review, then the comment fields …
<%= f.hidden_field :review_id %>
<p>
<label for="title">Title</label>
<%= f.text_field :new_comment_title, :size => 40 %>
</p>
<p>
<label for="comment">Body</label>
<%= f.text_field :new_comment_body, :size => 200 %>
</p>
<%= submit_tag "Save Comment", :class => "submit" %>
<% end %>
My review.rb model has:
acts_as_commentable # yeah, this seems fine
attr_accessor :new_comment_title # do I really need this??
attr_accessor :new_comment_body # ditto
attr_accessor :review_id # c’mon, this can’t be necessary!
and my controller has
def show_review
@review = Review.find(params[:id]) # fine
@review.review_id = @review.id # Save for later, but … should
I?
end
def save_comment
@comment = Comment.new # fine, I guess.
@comment.title = params[:review][:new_comment_title] # seems
complicated
@comment.comment = params[:review][:new_comment_body] # ditto
@review = Review.find(params[:review][:survey_id]) # from saved
for later
@review.add_comment(@comment) # fine
redirect_to(:back)
end
Sure, it works, but there has to be a simpler way than defining
comment-specific variables in my model, and subsequent references in my
controller.
What say ye, oh gods of Rails? Striketh me down with thy wisdome and
simplicitie!
Tom “Dunce Boy”