Rails控制器及路由基礎

在控制其中指定特定的layout頁面
class ExampleController < ApplicationController
    layout 'my_layout' # 將會使用 app/views/layouts/my_layout.html.erb
end
永遠不要相信用戶提交的數據

咱們必需要對用戶提交的數據進行過濾html

def article_params
     #咱們只提取title,location,excerpt,body,published_at,其餘的數據不用處理
      params.require(:article).permit(:title, :location, :excerpt, :body, :published_at) 
 end
在視圖中綁定數據
<%= render 'header', :title => 'My Blog' %>

咱們在模板中能夠這樣子使用session

<% title %>
嵌套路由中的表單提交url設置
form_for([@article, @article.comments.new]) #至關與

 form_for(:comment, @article.comments.new, url: [@article, @article.comments.new])

也能夠用下面的方式app

form_for(:comment, @article.comments.new, url: article_comments_path(article_id: @article))

更簡單直接的方法以下:
:控制器名,:url:xxx_path
less

在模板中使用控制器方法

例如咱們在ApplicationController中有一個方法以下ui

def current_user
        return unless session[:user_id]
        @current_user ||= User.find_by_id(session[:user_id])
    end

咱們就能夠在ApplicationController使用下面的方法,使得它能夠在模板中使用
helper_method :current_userurl

相關文章
相關標籤/搜索