Joe
Joe

Reputation: 379

How to access data in rails from a view that was created in the controller?

I am trying to pass an instance variable from the controller to the view. Not sure what I am doing wrong since the view can create an instance and get data. I can also get data in the console. When I inspect the instance instantiated in the controller it is nil. I can't even pass a string. Can anyone spot my error?

Controller tries to set Test. I know its being called because if I delete the line "render :layout => false" I can see the effects.

class ViewviewerimageController < ApplicationController

   def index

        render :layout => false

        @Test = 'XXX'

   end

end

And the view:

<!DOCTYPE HTML>

<html>
<head>


    <%= stylesheet_link_tag "ERP" %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>

    <title>Image Data</title>


</head>
<body>

    <%= render template: "layouts/header" %>
    <%= render template: "layouts/sidebar" %>


    <div id="content">

        Test = <%= @Test %><br>
        inspect = <%= @Test.inspect %><br>

    </div>

    <%= render template: "layouts/footer" %>

</body>
</html>

And what I get back is:

Test =
inspect = nil

I followed a few different tutorials but it seems they left out something and I can't seem to puzzle it out. I even deleted the CSS and javascript to see if they are interfering but just as I suspected, it wasn't them.

Upvotes: 2

Views: 392

Answers (1)

Ojash
Ojash

Reputation: 1234

It is because you have the instance variable created after the render is called.
Try doing this

def index
  @Test = 'XXX'
  render layout: false
end

Upvotes: 3

Related Questions