Understanding Controllers in Ruby-on-Rails - Rails in the Real World
(Page 4 of 4 )
As mentioned in the previous part, it is still not time for heavy-duty examples. They will be coming once the ActiveView and ActiveRecord have been discussed which will be covered in the near future. For this part, I will extend the example showing the time in the view created in the last part. If you remember, I created a controller having the following code:
classSayController < ApplicationController
defhello
end
end
and the view(hello.rhtml) having this code:
<html>
<head>
<title>Hello, Rails!</title>
</head>
<body>
<h1>Hello from Rails! The time now is <%=Time.now%></h1>
</body>
</html>
But this is a bad design since the code for displaying date(in bold) is within view. View shouldn’t be doing this. So let's move it to the controller because it is the right place for the code to be:
classSayController < ApplicationController
defhello
@time=Time.now
end
end
Now the current time value is stored in an instance variable time. Now it can be called from the view thus:
<html>
<head>
<title>Hello, Rails!</title>
</head>
<body>
<h1>Hello from Rails! The time now is <%=@time%></h1>
</body>
</html>
That’s it. In the next part I will be looking at the ActionView, the View Component of RoR. From then on I will be discussing the working of a real application, Library Management. Till then…
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |