2016-11-05 2 views
0

restaurants에 대한 스캐 폴딩 방법을 사용하여 레일에 간단한 레일 앱을 만들었습니다.레일즈는 컨트롤러에서 뷰로 인스턴스 변수를 어떻게 전달합니까?

restaurants_controller.rb의 컨트롤러를 표시하고 편집하는 방법입니다.

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

    # GET /restaurants/1/edit 
    def edit 
    end 

restaurants/show.html.erb 다음과 같습니다 :

<p id="notice"><%= notice %></p> 

<%= image_tag @restaurant.image_url %> 

<p> 
    <strong>Name:</strong> 
    <%= @restaurant.name %> 
</p> 

<p> 
    <strong>Address:</strong> 
    <%= @restaurant.address %> 
</p> 
... 

restaurants/edit.html.erb : 여기

<h1>Editing Restaurant</h1> 

<%= render 'form', restaurant: @restaurant %> 

<%= link_to 'Show', @restaurant, class: "btn btn-link" %> | 
<%= link_to 'Back', restaurants_path, class: "btn btn-link" %> 

내 질문은 : 그들은 단지 빈 방법이 얼마나 주목 내 현재의 이해 (잘못 될 수)입니다 인스턴스 변수 인이 경우에는 @restaurantrestaurant_controllers.rb에 정의하고, Rails는 contr에 정의 된 변수를 자동으로 연결합니다 보기에 oller. 레스토랑 컨트롤러 예를 들어, 인덱스 방법 : 나는 index.html.erb에서 @restaurants를 호출 할 때

def index 
    @restaurants = Restaurant.all 
end 

, 레일 views에 사용되는 인덱스 방법에서 @restaurants가 나타납니다. 비어있는 방법은

어디 레일 restaurants_controller.rb에도 불구하고 showedit 방법에서 @restaurant 인스턴스 show.html.erb에서 변수 edit.html.erb 나올까요입니까? 나는 5

+0

컨트롤러에'before_action : set_restaraunt'이 있습니까? –

+0

컨트롤러에'load_and_authorize_resource'와 함께 CanCan을 사용하고 있습니까? – David

답변

0

그래서 당신이 필요하지 않은 경우 모든 행동에

@test = Test.find(params[:id])를 추가하는 것과 같은 선량 생성 발판

class TestsController < ApplicationController 
before_action :set_test, only: [:show, :edit, :new, :update, :destroy] 

private 

    def set_test 
    @test = Test.find(params[:id]) 
    end 
end 

이를 적용하여 acheives이 레일 레일을 사용하고 있습니다 ..

다음,

메신저없는 레일 프로 before_action에 의해 정의 된 행동에 인스턴스 변수를 설정

, 그래서이있을 수 있습니다 이것에 대한 훨씬 더 나은 대답이지만, 나는 레일 매직에 질문하지 않는 것을 배웠다.

+0

그리고 자신 만의 MVC를 생성하고 위의 동일한 연습을 적용하면 동일한 작업을 수행 할 수 있습니다. –

관련 문제