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

Connected User to Post

parent f5ff1994
class PostsController < ApplicationController class PostsController < ApplicationController
before_action :authenticate_user! before_action :authenticate_user!
def index def index
@posts = Post.all @posts = current_user.posts
end end
def show def show
...@@ -9,11 +9,11 @@ class PostsController < ApplicationController ...@@ -9,11 +9,11 @@ class PostsController < ApplicationController
end end
def new def new
@post = Post.new @post = current_user.posts.new
end end
def create def create
@post = Post.new(post_params) @post = current_user.posts.new(post_params)
if @post.save if @post.save
redirect_to posts_path, notice: "You have successfully created a new post." redirect_to posts_path, notice: "You have successfully created a new post."
...@@ -50,4 +50,4 @@ class PostsController < ApplicationController ...@@ -50,4 +50,4 @@ class PostsController < ApplicationController
def post_params def post_params
params.require(:post).permit! params.require(:post).permit!
end end
end end
\ No newline at end of file
class Post < ApplicationRecord class Post < ApplicationRecord
end belongs_to :user
end
\ No newline at end of file
...@@ -3,4 +3,13 @@ class User < ApplicationRecord ...@@ -3,4 +3,13 @@ class User < ApplicationRecord
# :confirmable, :lockable, :timeoutable and :omniauthable # :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable :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 @@ ...@@ -15,6 +15,7 @@
<thead> <thead>
<th>Title</th> <th>Title</th>
<th>Content</th> <th>Content</th>
<th>Posted by</th>
<th colspan="3"></th> <th colspan="3"></th>
</thead> </thead>
<tbody> <tbody>
...@@ -26,6 +27,9 @@ ...@@ -26,6 +27,9 @@
<td> <td>
<%= post.content %> <%= post.content %>
</td> </td>
<td>
<%= post.user %>
</td>
<td> <td>
<%= link_to "Show", post_path(post), class: "btn btn-primary" %> <%= link_to "Show", post_path(post), class: "btn btn-primary" %>
</td> </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