2012-05-07 2 views
6

저는 Michael Hartl의 튜토리얼 을 통해 갈 것입니다. 기본적으로 사용자가 메시지를 게시하고 다른 사용자는 답글을 남길 수있는 게시판 응용 프로그램입니다. 지금은 Users을 만들고 있습니다. UsersController 일들은 다음과 같이 내부 :특정 ActiveRecord 객체와 함께 redirect_to를 사용하여 해당 객체에 대한 링크를 만듭니다

class UsersController < ApplicationController 
     def new 
     @user = User.new 
     end 

     def show 
     @user = User.find(params[:id]) 
     end 

     def create 
     @user = User.new(params[:user]) 
     if @user.save 
      flash[:success] = "Welcome to the Sample App!" 
      redirect_to @user 
     else 
      render 'new' 
     end  
     end 
    end 

을 저자는 다음과 같은 라인이 동일하다는 것을 말한다. 어느 나에게 의미가 있습니다 :

@user = User.new(params[:user]) 
    is equivalent to 
    @user = User.new(name: "Foo Bar", email: "foo[email protected]", 
      password: "foo", password_confirmation: "bar") 

redirect_to @usershow.html.erb로 리디렉션합니다. 그게 정확히 어떻게 작동합니까? show.html.erb에 가면 어떻게됩니까?

답변

13

이것은 레일의 편안한 라우팅의 마법을 통해 처리됩니다. 특히 특정 개체를 redirect_to으로하면 해당 개체의 show 페이지로 이동한다는 규칙이 있습니다. Rails는 @user이 활성 레코드 객체라는 것을 알고 있기 때문에, 객체의 표시 페이지로 가고 싶다는 것을 알고 있다고 해석합니다.

# If you wanted to link to just a magazine, you could leave out the 
# Array: 

<%= link_to "Magazine details", @magazine %> 

# This allows you to treat instances of your models as URLs, and is a 
# key advantage to using the resourceful style. 

는 기본적으로, 당신의 routes.rb 파일에 편안한 자원을 사용하여 직접 액티브 오브젝트에서 URL의 작성을위한 당신 '바로 가기'를 제공합니다

다음은 Rails Guide - Rails Routing from the Outside In.의 해당 섹션에서 일부 세부 사항입니다. 당신이 redirect_tosource code의 모습을 촬영하면

1

, 당신은 객체가 @article, url_for (@article입니다 있다고 가정은 객체로 url_for 함수를 호출하는 redirect_to_full_url(url_for(options), status), 시도를 반환합니다, 마침내 것을 알 수 있습니다)는 다음과 같이 반환합니다 "http://localhost:3000/articles/11를", 즉 라우팅에서 다음,이 URL에 대한 새로운 요구 될 것입니다, 당신은 또한 입력하여 콘솔의 경로를 확인할 수 있습니다

rake routes

의지가 SHOW 조치를 이동하고 show.html.erb에 렌더링하는 이유

는 그래서입니다. 희망이 당신의 질문에 대답했습니다.

관련 문제