Reputation: 379
I am trying to get data into my view from my controller in a rails app. I can instantiate the model in the view and it works. But when I try from the controller it fails. I can't seem to find nor figure out the technique. Can someone provide an example? The table is actually a view (on SQL server 2005) but I get the same results with a table.
Controller:
class ViewviewerimageController < ApplicationController
def index
@Viewviewerimage = Viewviewerimage.last
end
end
Model:
class Viewviewerimage < ActiveRecord::Base
self.table_name = "viewviewerimages"
self.primary_key = 'ImageID'
end
View:
<!DOCTYPE HTML>
<html>
<head>
<title>Image Data</title>
</head>
<body>
<%= render template: "layouts/header" %>
<%= render template: "layouts/sidebar" %>
<div id="content">
Table
<% i = TblImage.first %>
[obj] = <%= i %><br>
ID = <%= i.DocumentNbr %><br>
<br>
View<br>
<% the = Viewviewerimage.first %>
[obj] = <%= the %><br>
Size = <%= the.Size %><br>
Fails (prints nothing)
[obj] = <%= @Viewviewerimage %><br>
<br>
</div>
<%= render template: "layouts/footer" %>
</body>
</html>
This is really holding me up so any assistance is appreciated.
Stackoverflow seems to prohibit me from editing my comment so I will post it here.
This is my view app\views\viewviewerimage\index.html.erb.
I tried to reference a member from the @Viewviewerimage and receive "NoMethodError in Viewviewerimage#index" which seems to match getting nothing. When I print [obj] = the I get a hex number which makes sense, it is an object.
[obj] = #<Viewviewerimage:0x620b3f8 >
I get nothing when I print @Viewviewerimage.
[obj] =
Also . . .
<% the = @Viewviewerimage %>[obj] = <% the %> does the same thing as [obj] = <% @Viewviewerimage %>
The answer is here: How to access data in rails from a view that was created in the controller?
I omitted several lines of code and one of them was causing the problem. I had a render :layout => false before the instance was being created. Apparently this does not work. Moving it to the end solved the issue.
Upvotes: 2
Views: 1178
Reputation: 974
I think one of your biggest problems is naming things. A class called Viewviewerimage (view-viewer-image?) makes no sense. Also pay attention to CamelCasing and naming_your_files correctly.
When I try running your example code it seems to be working, so I guess you might have some confusing filenames here or there. When debugging your objects, you can always use .inspect
to show them in the view. If you put <%= @Viewviewerimage.inspect %>
in your view that corresponds to your controller you should see the model.
In your scenario make sure your controller goes into:
app/controllers/viewviewerimage_controller.rb
and that you have a route:
resources :viewviewerimage
I suggest renaming the lot at least to something like class ViewViewerImage
, putting it in a file named view_viewer_image.rb
, same goes for the controller.
Upvotes: 2