I'm studying Ruby On Rails. I'm asking a question because I have a question while reading the book and copying the example. It is said that if you register resource :name with the router now, you can use the defined method, but I am not sure how it works.
The controller code is as follows. Click the button to insert 1 to 10 into the Post Division. And that's how the index shows it.
class HomeController < ApplicationController
def index
@posts =Post.all
end
def write
1.upto(10) do |s|
local = "/home/ubuntu/workspace/app/views/home/#{s}.html.erb"
if not File.exists?(local)
postDB = Post.new
postDB.title = s
puts s
postDB.save
aFile = File.new( local, 'w')
if aFile
puts aFile.syswrite("<h1>")
puts aFile.syswrite(s)
puts aFile.syswrite("</h1>")
aFile.close
end
else
puts 'Unable open file'
end#else
end # 1 to 10
redirect_to "/home/index"
end
end # end class
When the code is executed, data from 1 to 10 is accumulated in the DB, and html files are also generated as shown below.
router.rb
Rails.application.routes.drawdo
get 'home/index'
post 'home/write'
get 'post/:2' => 'home#art#2'
get 'post/:3' => 'home#3'
resources :post
# # The priority is based upon order of creation: first created -> highest priority.
# # See how all your routes lay out with "rake routes".
# # You can have the root of your site routed with "root"
root 'home#index'
end
The bottom is the screen that you can see it. If you press the 3rd show here, it shows the 3.html screen as I want. I registered with the router.
However, if you press another show that you have not registered (excluding number 3), the following error message appears.
I have two questions here. First, resource:post to the router In other words, I wonder how to use the benefits of registering a post database. For example, in order to show you the HTml from 1 to 10, get 'post/:1' => 'home#1' get 'post/:2' => 'home#2' Should I set it up to 10 like this?
And when I create a random file called home/art, how can I show the router settings for the 2.html.erb in this file?
ruby-on-rails-4
get 'post/:2' => 'home#art#2'
get 'post/:3' => 'home#3'
resources :post
resources :post This code has been automatically scoped
If you made it with the rails command, there will be a Post Controller automatically, but if not, you will have to write it according to the route you see.
I think it's annoying to make it yourself, so I recommend you to make it again with scaffolding.
If you want to render a file other than the one already specified, you can use the render function
render template: "products/show"
It can be used in this format.
http://guides.rubyonrails.org/layouts_and_rendering.html
More detailed in this document
© 2024 OneMinuteCode. All rights reserved.