Let's say I did this:
script/generate controller home
And in the home controller made a the method..
def say
puts "You are here"
end
How would I call that method in the index.html.erb?
When learning ruby it just said to run the whatever.rb in the terminal to run what ever code you wrote within that file. Just curious on how that would work with rails.
I assume you have a rails server running?
Theres two possibilities, firstly you could make say a helper method in the controller by using:
helper_method :say
in your controller.
Alternatively, the better solution would be move your say method to the home_helper(?).rb helper file.
you can call this by just using <% say %> in your view file.
Note that a puts
well put whatever is in your string to STDOUT, not output in your views, if all you wanna do is write a bit of text, you would be better off with just outputting a string and using the erb output mechanism in your view, e.g.
application_helper.rb
def say
"hello"
end
index.html.erb
<%= say -%>
puts is very useful for unit test debugging where you wanna find out the contents of an object
puts @some_object.inspect
Whereas if you want output to the log, you could do something like:
logger.error "hello"
In short: You don't do that.
What you do is:
You call an action on a controller. For each action, there is a corresponding view, e.g. "say.html.erb" in the directory views/home.
To call that action, and display its corresponding view, you could do something like <%= link_to 'Say it', :controller => 'home', :action => 'say', :someadditionalparameter => 'foo' %>
in your index.html.erb
If you wanted to access :someadditionalparameter
in the say
action, you would do so with params[:someadditionalparameter]
and would, in this case, get 'foo'
.
Well, the view doesn't usually call the controller - it goes the other way around, from what I know. The request comes in, Rails parses the URL according to your config/routes.rb routes, and it forwards the request to the appropriate action in the appropriate controller. By default, Rails supplies a route for /controller_name/action_name, so you can use that for simple messing around with what Rails does for you.
After the controller has run, Rails automatically renders the associated view, which by convention has the same name as its action. The automatically-used view for your 'say' action in the 'home' controller would be found in your directory structure under app/views/home/say.html.erb. You can override this automatic view rendering by calling render
in your controller action, for example render :template => :index
.
And lastly, like Konstantinos said, you need to start the server before you can browse to the site in a web browser. It'll be at http://127.0.0.1:3000/
by default; to reach the home controller's say action, you'd go to http://127.0.0.1:3000/home/say
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With