开发者

Rails form problem

开发者 https://www.devze.com 2023-03-08 13:17 出处:网络
Have a boolean field (using formtastic) and the value won\'t persist through an error. If submitted and an error exists, on reload, the boolean field automatically checks itself, which is bad. I can s

Have a boolean field (using formtastic) and the value won't persist through an error. If submitted and an error exists, on reload, the boolean field automatically checks itself, which is bad. I can see the problem is in the conflicting value, hidden is 0 whereas the input is 1. Both should be 0. How do I correct this so both are set to 0 initially. Where am I going wrong?

Form Code:

<%= f.input :legal, :as => :boolean %>

Html Generated

<li class="boolean optional" id="user_legal_input">
   <input name="user[legal]" type="hidden" value="0" />
   <label for="user_lega开发者_如何学运维l">
      <input id="user_legal" name="user[legal]" type="checkbox" value="1" />I Agree to the legal terms
   </label>
</li>

ADDED: User (Create) Controller

def create
    @user = User.new(params[:user])
    respond_to do |format|
      if @user.save
        format.js  
      else
        format.js  
      end  
    end
  end

The js just re-renders the form with all the errors inline


the hidden field is always set to "0" to mimic an unchecked box, this is correct behaviour: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

Instead I suggest your isssue is your accessor method in the model.

The checkbox input is checked if @user.legal is true type, or more precisely if

ActionView::Helpers::InstanceTag.check_box_checked?(@user.legal,"1")

evaluates to true.

Now if legal is a boolean database column, rails initializer will convert it to ruby boolean so if you do

@user = User.new(:legal => "0")

then

@user.legal == false

but if legal is not a db column (otherwise :as => :boolean is unnecessary), then you must have defined an accessor method somehow.

If you did it with a simple attr_accessor then,

@user.legal == "0"

which correctly evaluates to an unchecked box.

but if you or your framework wanted to outsmart rails and you define:

attr_writer :legal
def legal
 !!@legal
end

or something similar under the hood (to give you a proper boolean back), then you are in trouble:

Here initial form display !!nil is false => unchecked box. but on submit/reload !!"0" is true => checked box.

let me know if my hunch is correct :)

0

精彩评论

暂无评论...
验证码 换一张
取 消