Why is the first element always blank in my Rails multi-select, using an embedded array?

后端 未结 9 2376
我寻月下人不归
我寻月下人不归 2020-11-29 19:54

I\'m using Rails 3.2.0.rc2. I\'ve got a Model, in which I have a static Array which I\'m offering up through a form such that users may se

9条回答
  •  清酒与你
    2020-11-29 20:23

    http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

    Gotcha

    The HTML specification says unchecked check boxes or selects are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like

    @invoice.update(params[:invoice]) wouldn't update the flag.

    To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.

    This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.

    To remove blank values:

      def myfield=(value)
        value.reject!(&:blank?)
        write_attribute(:myfield, value)
      end
    

提交回复
热议问题