Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio Button Helper - Default value

I have a table rooms and I have a field type(Single, Double). I want to use a radio button for this field. So, I am using it like this:

<% form_for(@room) do |f| %>
  <%= f.radio_button :type, "Single" %>
  <%= f.radio_button :type, "Double" %>
<% end %>

This works fine for edit view. The problem is that for the new view, I want to default the radio button to "Single". For this code, no value is checked for the new view.

I am now adjusting that with condition check

<% form_for(@room) do |f| %>
  <%= f.radio_button :type, "Single", :checked => @room.new_or_single? %>
  <%= f.radio_button :type, "Double" %>
<% end %>

Room model

def new_or_single?
  type.nil? or type == "Single"
end

Is there a better way to achieve this?

like image 329
rubyprince Avatar asked Dec 21 '22 14:12

rubyprince


1 Answers

Set default :type in constructor

def new
  @room = Room.new(:type => "Single")
end
like image 58
Sector Avatar answered Jan 05 '23 22:01

Sector