I'm a newby in Rails, and trying to use methods in html.erb instead of writing the same query several times. I've started with "Hello, World"; but, I couldn't even manage to do this. What I do;
def Say()
"Hello World"
end
in app/models/sample.rb (sample is the name of the page by the way) and
<% Say %>
in views/samples/index.html.erb. The problem is, obviously, I cannot see anything like "Hello World" on the page. What should I do?
There are a number of things here:
@say = 'Hello World'
in a controller method def index
and then calling in view <%= @say %>
will also do the trick, but don't get used to this approach as it commonly leads to bad habits like overuse of controller instead of models and helpers Maybe the best is to start tutorials from scratch and see how it is handled in rails. There are a lots of resources in rails on website: http://railscasts.com .
Even the site hasn't been updated for quite some time, I think the best resource is to start from there, especially for newbies.
There is helpers directory. You can create your own modules there or use default one: ApplicationHelper, which should exists in this dir. Let's create your own module.
The following makes the Say helper method available to the view:
module MyCustomHelper
def say
"Hello World"
end
end
In a view:
<%= say %>
Add helper module in your controller like(Rails 3):
class ApplicationController < ActionController::Base
helper :my_custom
end
or
class ApplicationController < ActionController::Base
helper_method :my_custom
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.