How does rails pass instance variable from controller to views? -


i created simple rails app in rails using scaffolding method restaurants.

this show , edit controller method restaurants_controller.rb. notice how blank methods:

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

this 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> ... 

and 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" %> 

here question: current understanding (could wrong) define instance variable, in case, @restaurant in restaurant_controllers.rb, , rails automatically connects variables defined in controller views. example, index method in restaurant controller:

def index   @restaurants = restaurant.all end 

when call @restaurants in index.html.erb, rails brings @restaurants index method used in views.

where rails @restaurant instance variable in show.html.erb , edit.html.erb though show , edit method in restaurants_controller.rb empty methods? using rails 5.

so rails acheives applying generated scaffolds

class testscontroller < applicationcontroller  before_action :set_test, only: [:show, :edit, :new, :update, :destroy]   private    def set_test     @test = test.find(params[:id])   end end 

that dose same adding

@test = test.find(params[:id]) every action if don't need to..

that then, sets instance variable on actions defined before_action

im no rails pro, there may better answer this, have learned not question "rails magic".


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -