Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Display variable from controller in view

I'm pretty new to rails and I was wondering how I can display a variable from my controller into my view.

Basically, I have 2 files: articles_controller.rb and _article.html.erb

In my controller file I have a variable @article_votes that I want to display on my view. I've tried using <%= @article_votes %> but it does not display anything at all.

Would anyone have any guidance? Thank you!

like image 810
Ben Avatar asked Jul 25 '11 06:07

Ben


People also ask

How do you add Ruby code inside rails views and have its result outputted in the HTML file?

The most popular way to add Ruby code inside Rails views is with embedded Ruby (ERB). Files with embedded Ruby have the extension . html. erb and these files can have any amount of regular html markup.

What are partials in Rails?

A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.


1 Answers

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.

like image 176
nathanvda Avatar answered Oct 08 '22 23:10

nathanvda