How can I make a check box default to being “checked” in Rails 1.2.3?

前端 未结 7 1123
攒了一身酷
攒了一身酷 2021-02-06 21:38

How can I make a check box default to being \"checked\" when it is initially displayed?

I\'ve not found a \"Rails\" way to do this (that works) so I did it with JavaScr

7条回答
  •  旧时难觅i
    2021-02-06 22:06

    This works on Rails 2.3.x and Rails 3.0.x!

    On action new in the controller, the check box is set to true.

    # in the controller
    def new
      @user = Person.find(:first)
      @user.active = true
    end
    

    In the form: the check box is checked on creation (by call new) but if the validation fails the check box remains set with the value that the user has post.

    # in the view
    <%= form_for ..... |f| %>
      ...
      <%= f.check_box :active %>
      ...
    <% end %>
    

    An other way, but not so good (if you want to change the logic you have to make a new migration) is to set :default => 1 in the migration of the given model and attribute.

    class CreatePeople < ActiveRecord::Migration
      def self.up
        create_table :people do |t|
          ...
          t.boolean    :active,             :null => false,
                                            :default => 1
          t.timestamps
        end
      end
    
      def self.down
        drop_table :people
      end
    end
    

提交回复
热议问题