Learn Rails5.2 Routes摘录
Posted chentianwei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Learn Rails5.2 Routes摘录相关的知识,希望对你有一定的参考价值。
Naming a Route
get ‘home/index‘, as: "different_name"
会得到prefix: different_name代替home_index, 这个是路径的名字。
get ‘home/ping‘, to: "home#pong"
to方法,定义到哪个控制器的哪个action。 这会改变默认的控制器的action。而控制器会指向view。
Paramter
通过浏览器输入的URI Pattern ,可以导向控制器的某个action
在router.rb中
resources :posts
get ‘:year(/:month(/:day))‘, to: ‘posts#index‘
Verb URI Pattern Controller#Action
GET /:year(/:month(/:day))(.:format) posts#index
解释:这里参数:year是必须的,括号里的是可选的。
http://localhost:3000/2018/01/01
Started GET "/2018/01/01" for 127.0.0.1 at 2018-06-18 09:52:25 +0800
Processing by PostsController#index as html Parameters: {"year"=>"2018", "month"=>"01", "day"=>"01"}
Rendering posts/index.html.erb within layouts/application
Post Load (0.1ms) SELECT "posts".* FROM "posts"
? app/views/posts/index.html.erb:16
Rendered posts/index.html.erb within layouts/application (1.8ms)
Completed 200 OK in 39ms (Views: 37.7ms | ActiveRecord: 0.1ms)
解释:在controller的index动作中, 你可以利用params[]来存取定义在URL中的值。
valid_date?方法,找不到出处?
def index
if Date.valid_date?(params[:year].to_i, params[:month].to_i, params[:day].to_i)
start_date = Date.parse("#{params[:day]}.#{params[:month]}.#{params[:year]}")
end_date = start_date
elsif Date.valid_date?(params[:year].to_i, params[:month].to_i, 1)
start_date = Date.parse("1.#{params[:month]}.#{params[:year]}")
end_date = start_date.end_of_month
elsif params[:year] && Date.valid_date?(params[:year].to_i, 1, 1)
start_date = Date.parse("1.1.#{params[:year]}")
end_date = start_date.end_of_year
end
if start_date && end_date
@posts = Post.where(published_on: start_date..end_date)
end
end
constraints(constraints={})
用于限制url
get ‘:year(/:month(/:day))‘, to: ‘posts#index‘, constraints: {year: /d{4}/, month: /d{2}/, day: /d{2}/ }
也可以接受块:
constraints(id: /d+.d+/) do
resources :posts
end
加入??后,id只能输入1.1或者10.11的格式,否则会报告Routing Error.
Redirect(*args, &block)方法
用于返回到其他path。设置比较复杂。
get ‘:year/:month/:day‘, to: redirect("/%{year}/0%{month}/0%{day}"), constraints: { year: /d{4}/, month: /d{1}/, day: /d{1}/ }
还必须加上??,否则不能导航到控制器的index动作。
get ‘:year(/:month(/:day))‘, to: ‘posts#index‘, constraints: {year: /d{4}/, month: /d{2}/, day: /d{2}/ }
我的理解:第一行代码是返回到第二行代码的路径,然后再指向控制器的index动作。
Nested Resources
以上是关于Learn Rails5.2 Routes摘录的主要内容,如果未能解决你的问题,请参考以下文章
Learn Rails5.2- Scaffolding and REST
Ruby on Rails Installation(Learn Rails5.2)
Learn Rails5.2- ActiveRecord: Migration , spring的使用(不兼容的解决办法)
如何使用 scikit-learn 对大文本数据进行分类?
scikit-learn RandomForestClassifier 概率预测与多数投票
使用 ngrok 的条带 webhook 没有答案