How can I make a radio button selected by default?

1,293 views
Skip to first unread message

planon

unread,
Mar 29, 2011, 12:28:15 AM3/29/11
to SimpleForm
I need the default value to be "Lbs", and this is how I set it up:


=f.input :weight_unit, :label=>"Unit", :collection=>["Lbs","Kg"], :as=>:radio, :priority=>["Lbs"]


But it's not working. Does anyone know how this can be done?

Ingo Gambin

unread,
Mar 29, 2011, 1:50:24 AM3/29/11
to plataformate...@googlegroups.com, planon
my first choice to preset radio- or checkbox-selections would be setting them in the new-action of the according controller

#app/models/user.rb
class User < ActiveRecord::Base
  belongs_to :department
end

#app/models/department.rb
class Department < ActiveRecord::Base
  has_many :users
end

#app/controllers/users_controller.rb
  # GET /users/new
  # GET /users/new.xml
  def new
    @user = User.new
    @user.department_id= Department.find_by_name('IT')

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

#app/views/users/_form.html.erb 
<%= simple_form_for(@user) do |f| %>
  <%= f.input :name %><br />
  <%= f.input :age %>
  <%= f.association :department, :as => :radio %>
  <%= f.button :submit %>
<% end %>


In your case you might just preset your 'new' object in your objects controller new-action with the according string 

def new 
   @myobject = Myobject.new
   @myobject.weight_unit= "Lbs"
   respond_to
    ...
end

2011/3/29 planon <spocks...@gmail.com>

Carlos Antonio da Silva

unread,
Mar 29, 2011, 6:19:04 AM3/29/11
to plataformate...@googlegroups.com, Ingo Gambin, planon
You can also give the :checked option, Instead of :priority. It might not be an array also, if you don't want more than one item to be selected.
--
At.
Carlos A. da Silva
Reply all
Reply to author
Forward
0 new messages