Commit 0ac9c847 authored by John Noel's avatar John Noel

Connected User to Post

parent f5ff1994
class PostsController < ApplicationController
before_action :authenticate_user!
def index
@posts = Post.all
@posts = current_user.posts
end
def show
......@@ -9,11 +9,11 @@ class PostsController < ApplicationController
end
def new
@post = Post.new
@post = current_user.posts.new
end
def create
@post = Post.new(post_params)
@post = current_user.posts.new(post_params)
if @post.save
redirect_to posts_path, notice: "You have successfully created a new post."
......@@ -50,4 +50,4 @@ class PostsController < ApplicationController
def post_params
params.require(:post).permit!
end
end
end
\ No newline at end of file
class Post < ApplicationRecord
end
belongs_to :user
end
\ No newline at end of file
......@@ -3,4 +3,13 @@ class User < ApplicationRecord
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
has_many :posts
def to_s
if first_name && last_name
"#{first_name} #{last_name}"
else
email
end
end
end
\ No newline at end of file
......@@ -15,6 +15,7 @@
<thead>
<th>Title</th>
<th>Content</th>
<th>Posted by</th>
<th colspan="3"></th>
</thead>
<tbody>
......@@ -26,6 +27,9 @@
<td>
<%= post.content %>
</td>
<td>
<%= post.user %>
</td>
<td>
<%= link_to "Show", post_path(post), class: "btn btn-primary" %>
</td>
......
class AddUsersToPosts < ActiveRecord::Migration[5.2]
def change
add_reference :posts, :user, foreign_key: true
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment