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

后端 未结 9 2268
我寻月下人不归
我寻月下人不归 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:22

    Use jQuery:

    $('select option:empty').remove(); 
    

    Option to remove blank options from drop down.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-29 20:24

    Another quick fix is to use this controller filter:

    def clean_select_multiple_params hash = params
      hash.each do |k, v|
        case v
        when Array then v.reject!(&:blank?)
        when Hash then clean_select_multiple_params(v)
        end
      end
    end
    

    This way can be reused across controllers without touching the model layer.

    0 讨论(0)
提交回复
热议问题