What's New in Rails4 View?

Well, previouse article I had talked about What’s New in Rails4 ActiveModel?. Today We are looking at view:

Assume we have an owner class which has many items and each items are usualy belongs to an owner:

1
2
3
class Owner < ActiveRecord::Base
  has_many :items
end
1
2
3
class Item < ActiveRecord::Base
  belongs_to :owner
end

Select box
- Rails3 & 4
In Rails3 & 4 if we want to build a select box with owner we could do it with a single method called:

1
collection_select(:item, :owner_id, Owner.all, :id, :name)

Radio button & checkbox
- Rails3
In Rails3 we need do with the loops and builds each of the elements:

1
2
3
4
<% @owners.each do |owner| %>
  <%= radio_button_tag :owner_id, owner.id %>
  <%= owner.name %>
<% end %>

HTML output:

1
2
<input id="owner_id" name="owner_id" type="radio" value="1" /> Slow-draw
<input id="owner_id" name="owner_id" type="radio" value="2" /> Sheriff

- Rails4
Now in Rails4 we have collection_radio_buttons & collection_check_boxes method which builds all elements from a collection:

1
2
collection_radio_buttons(:item, :owner_id, Owner.all, :id, :name)
collection_check_boxes(:item, :owner_id, Owner.all, :id, :name)

Date field
- Rails3
At some points we must use date_select form helper:

1
<%= f.date_select :return_date %>

HTML output:

1
2
3
4
5
6
7
8
9
10
11
<select id="item_return_date_1i" name="item[return_date(1i)]">
  <option value="2008">2008</option>
  ...
</select>
<select id="item_return_date_2li" name ="item[return_date(2i)]">
  <option selected="selected" value="1">January</option>
  ...
</select>
<select id="item_return_date_3i" name="item[return_date(3i)]">
  ...
</select>

- Rails4
Rails4 now there is a date_field:

1
<%= f.date_field :return_date %>

HTML output:

1
<input id="item_return_date" name="item[return_date]" type="date">