Passing local variables to a view from controller

后端 未结 5 890
鱼传尺愫
鱼传尺愫 2021-02-14 05:57

I am not able for some reason to pass local variables to the show view...

In my controller i have simply:

def show
  render template: \"books/show\", :re         


        
5条回答
  •  别那么骄傲
    2021-02-14 06:36

    Passing Data from the Controller to the View

    Here's a NovelController class, to be put into app/ controllers/novel_controller.rb.

    class NovelController < ApplicationController
          def index
            @title = 'Shattered View: A Novel on Rails'
          end
    end
    

    Since this is the Novel controller and the index action, the corresponding view is in app/views/novel/index.html.erb

    <%= @title %>

    Output:

    Shattered View: A Novel on Rails
    

    The view is interpreted after NovelController#index is run. Here's what the view can and can't access:

    • It can access the instance variables @title, because they've been defined on the NovelController object by the time NovelController#index finishes running.
    • It can call instance methods of the instance variables @title.

提交回复
热议问题