This article can be read in 5 minutes. I found the relationship between rails' routing controller view to be a bit confusing, so I'll summarize it.
routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :posts #index to posts controller,Create all actions such as edit
end
rails g controller controller name
Controller name is plural of model and lowercase at the beginning of the sentence
class PostsController < ApplicationController
def index #Action name
@posts = Post.all.order(created_at: 'desc') #Define it with an instance variable
end
end
index.html.erb
<h2>My Posts</h2>
<ul>
<% @posts.each do |post| %>Use instance variables defined in controller actions
<li><%= post.title %></li>
<% end %>
</ul>
I want to use the variable @post defined in the index action in html, so I created an erb file that can embed Ruby. Ruby can be embedded in the part surrounded by <%%>. If you want to display the part where Ruby is embedded, add = to make it <% =%>.
You now have a posts controller index action and a corresponding view file. And I was able to confirm that the routing corresponding to the controller and the action is done in routes.rb.
I will deal with what the actually displayed data looks like in another article.
[Promotion] In my main business, I am a lecturer at a programming school. (But I'm still training.) We plan to update note and twitter, focusing on what we noticed as a lecturer. If you find this article helpful, please follow us. Nice to meet you!
Click here for note Click here for twitter
Recommended Posts