Sylar Sylar - 6 months ago 10
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"
end


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"
end


Still within the controller's class:

def languages_i_hate
languages = %w[
Perl
PHP
C#
C++ ]
end


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

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.

See http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method

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.