4

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?

1
  • 2
    You can set default value for type on 'single' in database schema or in the constructor. Commented May 3, 2011 at 10:19

1 Answer 1

11

Set default :type in constructor

def new
  @room = Room.new(:type => "Single")
end
Sign up to request clarification or add additional context in comments.

1 Comment

You also may want to consider changing your field name from 'type' to 'room_type'. The column name 'type' is a field that Active Record uses for inheritance. It may cause you problems later on: oldwiki.rubyonrails.org/rails/pages/MagicFieldNames

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.