Permalink
Browse files

Associate users with comments

  • Loading branch information...
1 parent dfa6996 commit 3056d0778b2caf468982eece12010107a311a58f @xmonkey committed Dec 14, 2012
@@ -1,7 +1,9 @@
class CommentsController < ApplicationController
+ before_filter :require_user, only: [:create]
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
+ @comment.user = current_user
if @comment.save
redirect_to @post
else
View
@@ -1,5 +1,6 @@
class Comment < ActiveRecord::Base
belongs_to :post
+ belongs_to :user
attr_accessible :content
validates :content, :presence => true
end
@@ -2,10 +2,14 @@
<p><%= pluralize(@post.comments.count, ' comment') %> </p>
<ul>
<% @post.comments.each do |comment| %>
- <li> <%= comment.content %> </li>
+ <li>
+ <%= comment.content %> by <i><%= comment.user.name %></i>
+ </li>
<% end %>
</ul>
-<%= form_for @post.comments.new, :url => post_comments_path(@post) do |f| %>
- <%= f.text_area :content, :size => "60x2" %>
- <%= f.submit "Add comment" %>
+<% if logged_in? %>
+ <%= form_for @post.comments.new, :url => post_comments_path(@post) do |f| %>
+ <%= f.text_area :content, :size => "60x2" %>
+ <%= f.submit "Add comment" %>
+ <% end %>
<% end %>
@@ -0,0 +1,5 @@
+class AddUserIdToComments < ActiveRecord::Migration
+ def change
+ add_column :comments, :user_id, :integer
+ end
+end
View
@@ -11,13 +11,14 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20121214073722) do
+ActiveRecord::Schema.define(:version => 20121214094120) do
create_table "comments", :force => true do |t|
t.text "content"
t.integer "post_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
+ t.integer "user_id"
end
add_index "comments", ["post_id"], :name => "index_comments_on_post_id"

0 comments on commit 3056d07

Please sign in to comment.