在控制其中指定特定的layout頁面
class ExampleController < ApplicationController
layout 'my_layout' # 將會使用 app/views/layouts/my_layout.html.erb
end
永遠不要相信用戶提交的數(shù)據(jù)
我們必須要對用戶提交的數(shù)據(jù)進行過濾
def article_params
#我們只提取title,location,excerpt,body,published_at,其他的數(shù)據(jù)不用處理
params.require(:article).permit(:title, :location, :excerpt, :body, :published_at)
end
在視圖中綁定數(shù)據(jù)
<%= render 'header', :title => 'My Blog' %>
我們在模板中可以這樣子使用
<% title %>
嵌套路由中的表單提交url設置
form_for([@article, @article.comments.new]) #相當與
form_for(:comment, @article.comments.new, url: [@article, @article.comments.new])
也可以用下面的方式
form_for(:comment, @article.comments.new, url: article_comments_path(article_id: @article))
更簡單直接的方法如下:
:控制器名,:url:xxx_path
<%= form_for :comment, url: article_comments_path(article_id: @article.id) do |f| %>
在模板中使用控制器方法
例如我們在ApplicationController
中有一個方法如下
def current_user
return unless session[:user_id]
@current_user ||= User.find_by_id(session[:user_id])
end
我們就可以在ApplicationController
使用下面的方法铡溪,使得它可以在模板中使用
helper_method :current_user