[RUBY] Rails routing controller view relationship

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.

Prerequisites
  • rails new has created an app directory
  • Rails g model modeled

Conclusion Remember this much!
  • Set controller and action for routing
  • Controller name = plural of model name and lowercase letters
  • File name of erb file ... Action name.html.erb
  • Put the instance variable defined in the action into an erb file Embed
  • erb file is created in app> views> controller name

Make sure the controller and actions are set for routing

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

Controller

Create
rails g controller controller name

Controller name is plural of model and lowercase at the beginning of the sentence

Controller description Controller name_controller.rb
class PostsController < ApplicationController
  def index #Action name
    @posts = Post.all.order(created_at: 'desc') #Define it with an instance variable
  end
end
  • Index: An action that displays a list page.

View file

index.html.erb

  • Make the character string before html correspond to the action of the controller. Created in app> views> controller name </ b>
<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