Reputation: 3
I have recently started learning Ruby on rails and going through various tutorials. Previously, I did code in PHP.
One of the practices I found in the tutorials is as below. I wanted to know, if this is the optimal way? What are the possible scenarios this is used?
For e.g, When generating a form in the views, the below code was used:
<h1>Contact us</h1>
<%= form_tag do %>
<%= label_tag ('Name') %>
<%= text_field_tag 'Name','Enter name here'%>
<%= label_tag ('Email') %>
<%= email_field_tag('Email', @email, options = {}) %>
<%= submit_tag "Edit this article" %>
<% end %>
Would it not a be a good practice to use HTML code directly in the view and just use ruby wherever dynamic stuffs are generated? Is there any reason I should use the methods to generate html other than the sole reason for faster coding (for people who are more familiar with ruby methods). Since, I am new at ruby, I would be faster coding HTML and use Ruby only when required and not for simple reasons of generating HTML.
What is the industry practice. Will getting into this habit of not using Ruby methods to generate html make it tough for me to read other's code?
Thanks for any responses in advance.
Upvotes: 0
Views: 141
Reputation: 11951
The ruby methods you're using are called helpers. They are there to do just that: help. At first, there's a lot to learn, but after learning them they save a great deal of time. Also, they aren't ruby methods, they belong to the rails framework - the language and the framework are two distinct things.
Here are some reasons why you should use the view helpers:
Upvotes: 0
Reputation: 1555
The helpers on Rails really helps, they are not there to make it more difficult. When you get used you feel great for using it.
Anyway you can still use html code directly, if you don't want to learn or use helpers you can do it, but you will be missing a cool thing in rails and certainly if it happens that you should work in a team I'm certain that the rest of the team will use the helpers and not html.
And rails promotes "convention over configuration", and one of the good points on that is to know that as a rails developer you will be able to work without much adaptation on any Rails project without getting lost looking for files, how is mvc working, and other stuff like that.
When you study and practice more the use of helpers you will start to see all the "power" of it, and see how much it really helps.
Upvotes: 0
Reputation: 13014
These are the methods of ActionView::Helper::FormHelpers
. They don't only generate the bare HTML markup. Apart from inserting the tags, they also add adequate id
, class
, data
attributes etc. The dynamically inserted id
for instance is responsible for creating the available params
hash, which in turn is responsible for most of the form actions in your controller.
You can try inserting that by directly using HTML, but two things will happen:
Upvotes: 1