2014-12-06 29 views
0

我開發了一個簡單的玩具應用程序,它使用腳手架來模擬用戶和微型帖子。這是我的user_controllerRails http休息架構

源 「railstutorial.org」

class UsersController < ApplicationController 
    before_action :set_user, only: [:show, :edit, :update, :destroy] 

    # GET /users 
    # GET /users.json 
    def index 
    @users = User.all 
    end 

方法顯示

# GET /users/1 
    # GET /users/1.json 
    def show 
    end 

# GET /users/new 
    def new 
    @user = User.new 
    end 

    # GET /users/1/edit 
    def edit 
    end 

    # POST /users 
    # POST /users.json 
    def create 
    @user = User.new(user_params) 

    respond_to do |format| 
     if @user.save 
     format.html { redirect_to @user, notice: 'User was successfully created.' } 
     format.json { render :show, status: :created, location: @user } 
     else 
     format.html { render :new } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

方法更新

# PATCH/PUT /users/1 
    # PATCH/PUT /users/1.json 
    def update 
    respond_to do |format| 
     if @user.update(user_params) 
     format.html { redirect_to @user, notice: 'User was successfully updated.' } 
     format.json { render :show, status: :ok, location: @user } 
     else 
     format.html { render :edit } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

# DELETE /users/1 
    # DELETE /users/1.json 
    def destroy 
    @user.destroy 
    respond_to do |format| 
     format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_user 
    @user = User.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def user_params 
    params.require(:user).permit(:name, :email) 
    end 
end 

顯示方法用於呈現類型爲「users/1」類型的URL的用戶頁面。

但更新方法是更新我們用戶的數據庫,但在更新操作被調用後,它會將我們重定向到「users/1」URL。

在第一種情況下,http請求的類型是「GET」,它將路由給「顯示」功能/操作,但是第二種情況是http請求的類型爲「PATCH」,它將控制路由到「更新」功能,函數只需更新數據庫,那麼爲什麼以及如何將我們重定向到「users/1」。它是否在任何地方調用任何渲染代碼?

我是初學者,所以如果問題有點傻,請原諒我,但如果有人能回答,這將是一個很大的幫助。

回答

1

看到你的代碼更新動作,如果@ user.update(user_params)後

要調用redirect_to時,它只是您重定向到您所提供它的新途徑。
在這種情況下,當您傳遞對象時,其重定向顯示動作,您也可以提供任何其他路由。

瞭解redirect_to的http://api.rubyonrails.org/classes/ActionController/Redirecting.html

+0

哦,謝謝。我不知道我是如何錯過它的。謝謝。 – 2014-12-07 02:19:04

0

@user是一個簡單的用戶條目對象誰在用戶模型得到了一個ID,如果你說redirect_to的@user,它會自動檢測用戶的@user和重定向發現ID到/用戶/:ID,鐵軌足夠了解,