Sylar Sylar - 2 years ago 76
Ruby Question

Rails 4: What Goes in Controller and Model?

I have been reading and watching few videos on learning Rails 4. All tutorials has their own code so, in my views, easy to follow. I can't seem to learn anything or remember few things so I have decided to use my own code and see if I could follow instead of using their code.

So far I understand the Controller corresponds with the views:

# In my controller
def index
@x = "I love Ruby"

And in my views (index.html.erb)

<% = @x %> #=> I love Ruby

That simple thing would work for the index page. Now what if want to refer other method calls in that view's index, how to do that? In the controller:

def index
@x = "I love Ruby"

Still within the controller's class:

def languages_i_hate
languages = %w[
C++ ]

And in my index.html.erb:

<%= These are the languages I hate to bits: #{languages_i_hate.upcase}!

I got undeclared method or variable "languages_i_hate"

How do I call method names in a webpage?

Answer Source

What you are trying to do here is access a controller method in the view. When you do this the controller method is accessed as if it was a helper method. Normally controller methods aren't available to be used in this way, but you can tell the controller to make them available as helpers.


BTW, when you have methods in the controller which aren't actions, ie don't correspond to a route/url, you should put them in a protected section, by convention at the bottom of the controller. This makes it clear to rails and to the reader that they're not actions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download