Huge mistake in last article.
Since we didn't create a Post object yet, the query:
rails console
>>> Post.find(3)
Won't return an object with ID = 3. Rather an empty object/ nil. Cos duh!?
My bad. Got distracted by everyday fantasy-land livin'
Let's write a rails form to create a new post today.
As we know, the new action in PostsController points to the new.html.erb file in views.
Yes. You guessed it right. We create our new @post object in the action :new.
And display it in the views.
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
# ...
end
end
We have successfully created a new Post instance @post.
Let's create a rails form to get the user input for @post attributes.
# app/views/posts/new.html.erb
<%= form_with model: @post do |form| %>
<%= form.label :title %>
<%= form.text_field :title %>
<br>
<%= form.label :body %>
<%= form.text_field :body %>
<% end %>
Rails provides form_with helpers. Please refer to the documentation here: guides.rubyonrails.org/form_helpers.html
Now we add methods to create action in our controller to store the input data and return a message.
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
flash[:notice] = "Post created successfully!"
redirect_to @post
else
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
The action :post_params uses the params helper provided by Rails to declare the permitted parameters.
The redirect_to callback renders the show.html.erb for the passed value @post.
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
# -> params[:id] accepts the attribute ':id' from Post model parameters.
end
end
# app/views/posts/show.html.erb
<h3><%= @post.title %></h3><br>
<p><%= @post.body %></p>
Before we go ahead with other methods :edit, :update and :destroy...
Let's take a quick peek at basic routes and validations at the next article.
Gud-buy!
Note:
- I might skip ahead a few steps from now on. I do not want to be another "Rails Tutorial" yet just want to share my learning experience as I am very new to the Rails framework as well.
- Please feel free to contact me through comments section or my mdevroot twitter if you need anything specific or report errors. Thank you.
- The Rails and Ruby have highly informative and precise documentation.
- Make sure to learn and understand Symbols in Ruby and how they are implemented in Rails.
Love,
M.
liked_the_post == true ? comment and share : comment and share