Deploy apps to servers that you own and control.
Application monitoring that helps developers get it done.
Now that our users can sign up and sign in to our application, we can turn our focus to the core of Lorem News—posts. To do this, we'll use Rails scaffolding to generate a Post resource.
Let's switch back to our command line and run the following command:
bin/rails generate scaffold Post 'user:belongs_to' 'title:string!:uniq' 'body:text!'
Running this command creates:
Let's inspect the migration file to ensure everything looks correct. Everything is set up properly. The posts table:
Before continuing, let's commit our changes.
Now, let's start our development server and see how it looks.
Navigating to /posts, we see no posts yet, but we can go to /posts/new to create one. However, the form currently asks for a user ID, which we need to remove and set automatically based on the logged-in user.
To ensure new posts are linked to the signed-in user, we update our Post controller:
We remove the user ID field from the form and set the user in the post controller:
def new
@post = Current.user.posts.new
end
def create
@post = Current.user.posts.new(post_params)
if @post.save
redirect_to @post, notice: "Post was successfully created."
else
render :new, status: :unprocessable_entity
end
end
...
def post_params
params.expect(post: [ :title, :body])
end
Here’s what’s happening:
To complete this, we need to define the relationship in our User model:
class User < ApplicationRecord
has_many :posts, dependent: :destroy
end
Now, each user can have many posts, and when a user is deleted, their posts will be removed as well (dependent: :destroy).
Next, we update the form view (_form.html.erb) to remove the user selection field:
<%= form_with(model: post) do |form| %>
<div>
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div>
<%= form.label :body %>
<%= form.text_area :body %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
Now, users don’t need to select their own ID—it’s handled automatically!
Navigating to /posts/new, we create a new post:
Submitting the form, we see:
We also made small UI improvements to flash messages, making them more noticeable when actions succeed or fail.
While the post submission works, there are some security enhancements we need to make:
We'll tackle these improvements in the next video to ensure our Rails and SQLite app is both secure and efficient.