Rails 3: Display variable from controller in view Rails 3: Display variable from controller in view ruby-on-rails ruby-on-rails

Rails 3: Display variable from controller in view


Not sure how new you are to rails. Any instance variable you define inside your controller is reachable inside the views.

So, if @article_votes is defined in the controller, writing

<pre>  <%= @article_votes.inspect %></pre>

somewhere in your view should show up in your page.

But the _article.html.erb is not shown by default. If you have a show method in your ArticlesController, the view called show.html.erb is rendered. This is a general approach, so for the index method, it should be called index.html.erb.

Hope this helps.


The output of <%= @article_votes %> will depend on what class the @article_votes is an object of and whether or not you are actually rendering that _article.html.erb template

Just call <%= render :partial => 'article' %> in the index.html.erb file or whatever .html.erb file is named after the controller action that you are using to try to render this view.

Normally coming from a controller @article_votes would be an array (by convention) plural names denote an array of objects and a singular name denotes a specific object of an ActiveRecord class based on a table called article_votes which would contain all the values held in the table for a specific record.

Make sure that @article_votes is an instance of a class other than nil

If it's just a string then (@article_votes = "A string") then you will see that in your view.If it's a result of a call ActiveRecord to find all objects from the ArticleVotes model then it will be an array which will be empty if nothing is in the table. You will need to get a specific object from that array and then you will need to choose which of the available methods on that object you wish to display

e.g.

Assuming the table article_votes has a column called name on it and you have 1 article_vote record in that table with the value of 'This is a name' then the following code in the a controller action would get you a display of "This is a name" on your screen

@article_vote = ArticleVote.first

If you had <%= @article_vote.name %> in your partial and assuming that you actually are rendering that partial


If you are calling a partial you will need to pass the @article_votes variable to it.

<@= render 'article', :article_votes => @article_votes %>

Now within your partial you can use

<%= article_votes %>