Permalink
Browse files

Associate user with post

  • Loading branch information...
xmonkey committed Dec 14, 2012
1 parent 951da52 commit dfa6996a1ccdae95a2d162058c6d0a56379cdbbf
@@ -9,5 +9,11 @@ def logged_in?
!!current_user
end
+ def require_user
+ if !logged_in?
+ redirect_to root_path, notice: "You need to sign in first"
+ end
+ end
+
helper_method :current_user, :logged_in?
end
@@ -1,4 +1,5 @@
class PostsController < ApplicationController
+ before_filter :require_user, only: [:new, :create]
def index
@posts = Post.all
end
@@ -13,6 +14,7 @@ def new
def create
@post = Post.create(params[:post])
+ @post.user = current_user
if @post.save
redirect_to posts_path
else
View
@@ -1,6 +1,7 @@
class Post < ActiveRecord::Base
has_many :comments
has_many :votes
+ belongs_to :user
attr_accessible :title, :url
validates :title, :presence => true
validates :url, :presence => true
@@ -2,6 +2,7 @@
<% @posts.each do |post| %>
<p>
<%= link_to post.title, url_link(post) %>
+ by <%= post.user.name %>
<%= link_to pluralize(post.comments.count, ' comment'), post %>
<%= pluralize(post.votes_count, ' vote' )%>
<%= link_to "upvote", post_votes_path(post, :vote => [:upvote =>true]), :method => :post %>
@@ -10,5 +11,6 @@
</p>
<% end %>
-
-<%= link_to "Submit a Link", new_post_path %>
+<% if logged_in? %>
+ <%= link_to "Submit a Link", new_post_path %>
+<% end %>
@@ -0,0 +1,5 @@
+class AddUserIdToPosts < ActiveRecord::Migration
+ def change
+ add_column :posts, :user_id, :integer
+ end
+end
View
@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20121214031603) do
+ActiveRecord::Schema.define(:version => 20121214073722) do
create_table "comments", :force => true do |t|
t.text "content"
@@ -27,6 +27,7 @@
t.string "title"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
+ t.integer "user_id"
end
create_table "users", :force => true do |t|

0 comments on commit dfa6996

Please sign in to comment.