Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

acts_as_commentable examples?

I have a model that I want to be commentable. I am having difficulty creating a form on my model's 'show' view that will allow comments to be created. I am not finding any good or useful examples. Can anyone point me to or show me an example of how to do this?

Example:

A simple blog application. I have a model called Post. It is commentable. So on the 'show' view I want to show a Post and, at the bottom, have the fields that, when completed and submitted, create a new comment associated with the post and put it in the database.

Sounds straightforward and I have it working so I can display comments that I have seeded. I just can't get a form to work to put new ones in. Any help is appreciated.

like image 993
NJ. Avatar asked Nov 02 '10 22:11

NJ.


2 Answers

Lets assume a Post model. Make sure, you have

class Post < ActiveRecord::Base
acts_as_commentable
end

then in the view of say Post#show

  <%= form_tag "/posts/add_new_comment" do %>
    <%= hidden_field_tag "id", post.id %>
    <%= text_area_tag "comment[comment]" %>
    <%= submit_tag "Post Comment" %>
  <% end %>

then in the PostController

  def add_new_comment
    post = Post.find(params[:id])
    post.comments << Post.new(params[:comment])
    redirect_to :action => :show, :id => post
  end

and in routes.rb

  match "/posts/add_new_comment" => "posts#add_new_comment", :as => "add_new_comment_to_posts", :via => [:post]

Hope this gets u up and running.

like image 124
Kunday Avatar answered Oct 14 '22 03:10

Kunday


This is very, very basic stuff and you clearly need some better structure and approach to your learning. Buying a book, such as Agile Web Development with Rails, is the only real way to learn, otherwise you'll wander from problem to problem without ever actually learning anything well.

Say you have a post that you want to comment.

#routes.rb
map.resources :posts do |post|
  post.resources :comments
end

#post_controller.rb
def show
  @post.find params[:id]
  @comment = @post.comments.new
end

#posts/show.html.erb
<%- form_for [@post, @comment] do |f|-%>
  <%= f.text_area :body -%>
  <%= f.submit -%>
<%- end -%>

#comments_controller
def create
  @post = @post.find params[:post_id]
  @comment = @post.comments.new params[:comment]
  if @comment.save
    redirect_to @post
like image 27
mark Avatar answered Oct 14 '22 03:10

mark