복붙노트

[RUBY-ON-RAILS] 루비는 사용자 지정 특성을 가진 f.select 옵션을 레일

RUBY-ON-RAILS

루비는 사용자 지정 특성을 가진 f.select 옵션을 레일

이 같은 형태 select 문을 가지고 :

= f.select :country_id, @countries.map{ |c| [c.name, c.id] }

어떤이 코드의 결과 :

...
<option value="1">Andorra</option>
<option value="2">Argentina</option>
...

하지만이 같은, 내 옵션에 사용자 정의 HTML 속성을 추가 할 :

...
<option value="1" currency_code="XXX">Andorra</option>
<option value="2" currency_code="YYY">Argentina</option>
...

해결법

  1. ==============================

    1.레일은 사용자가 기존의 options_for_select 도우미를 사용하여 옵션을 선택 속성을 추가 할 수 있습니다. 당신은 거의 바로 문제의 코드에서 있었다. HTML5의 데이터 속성을 사용하여 :

    레일은 사용자가 기존의 options_for_select 도우미를 사용하여 옵션을 선택 속성을 추가 할 수 있습니다. 당신은 거의 바로 문제의 코드에서 있었다. HTML5의 데이터 속성을 사용하여 :

    <%= f.select :country_id, options_for_select(
        @countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] }) %>
    

    초기 선택을 추가 :

    <%= f.select :country_id, options_for_select(
        @countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] }, 
        selected_key = f.object.country_id) %>
    

    당신이 그룹화 옵션이 필요하면 (@continents는 대륙 객체의 배열, 각각 국가 방법을 가진 경우),이 같은 grouped_options_for_select 도우미를 사용할 수 있습니다 :

    <%= f.select :country_id, grouped_options_for_select(
        @continents.map{ |group| [group.name, group.countries.
        map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] } ] }, 
        selected_key = f.object.country_id) %>
    

    신용에 폴 @ pogodan, 워드 프로세서에없는이를 찾는 것에 대해하지만 읽기에 의해 게시 누가이 레일 소스를 가야한다. https://web.archive.org/web/20130128223827/http://www.pogodan.com/blog/2011/02/24/custom-html-attributes-in-options-for-select

  2. ==============================

    2.다음과 같이이 작업을 수행 할 수 있습니다 :

    다음과 같이이 작업을 수행 할 수 있습니다 :

    = f.select :country_id, @countries.map{ |c| [c.name, c.id, { 'data-currency-code' => c.currency_code} ] }
    
  3. ==============================

    3.이 레일에 직접 수 없습니다, 당신은 사용자 지정 특성을 만들기 위해 자신의 도우미를 만들어야합니다. 그게 당신이 원하는 것을 달성하기 위해 두 가지 방법 아마가 말했다 :

    이 레일에 직접 수 없습니다, 당신은 사용자 지정 특성을 만들기 위해 자신의 도우미를 만들어야합니다. 그게 당신이 원하는 것을 달성하기 위해 두 가지 방법 아마가 말했다 :

    HTML5에서 사용자 정의 속성 이름을 사용하여 (1). HTML5에서는 사용자 지정 특성 이름을 가질 수 있습니다,하지만 그들은 '데이터 -'로 사전에 보류해야합니다. 이러한 사용자 정의 속성은 양식과 함께 제출되지 않습니다,하지만 그들은 자바 스크립트에서 요소에 액세스 할 수 있습니다. 이 작업을 수행하려면,이 같은 옵션을 생성하는 도우미를 만드는 것이 좋습니다 :

    <option value="1" data-currecy-code="XXX">Andorra</option>
    

    사용자 정의 분할 (2)를 사용하여 값을 추가 데이터를 제출합니다. 당신이 실제로 통화 코드를 제출하려는 경우,이 같이 당신의 선택 상자를 만드는 것이 좋습니다 :

    = f.select :country_id, @countries.map{ |c| [c.name, "#{c.id}:#{c.currency_code}"] }
    

    이것은 HTML을 생성해야하는 다음과 같다 :

    <option value="1:XXX">Andorra</option>
    <option value="2:YYY">Argentina</option>
    

    어떤 당신은 다음 컨트롤러에서 구문 분석 할 수 있습니다 :

    @id, @currency_code = params[:country_id].split(':')
    
  4. ==============================

    4.여분의 속성 해시은 레일 3에서 지원됩니다.

    여분의 속성 해시은 레일 3에서 지원됩니다.

    나는 기본적으로 그냥 레일 3 코드를 복사. 당신은이 3 가지 방법을 재정의해야합니다 :

    def options_for_select(container, selected = nil)
        return container if String === container
        container = container.to_a if Hash === container
        selected, disabled = extract_selected_and_disabled(selected)
    
        options_for_select = container.inject([]) do |options, element|
          html_attributes = option_html_attributes(element)
          text, value = option_text_and_value(element)
          selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
          disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
          options << %(<option value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{html_escape(text.to_s)}</option>)
        end
    
        options_for_select.join("\n").html_safe
    end
    
    def option_text_and_value(option)
      # Options are [text, value] pairs or strings used for both.
      case
      when Array === option
        option = option.reject { |e| Hash === e }
        [option.first, option.last]
      when !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
        [option.first, option.last]
      else
        [option, option]
      end
    end
    
    def option_html_attributes(element)
      return "" unless Array === element
      html_attributes = []
      element.select { |e| Hash === e }.reduce({}, :merge).each do |k, v|
        html_attributes << " #{k}=\"#{ERB::Util.html_escape(v.to_s)}\""
      end
      html_attributes.join
    end
    

    좀 지저분하지만 옵션입니다. 나는 다음 ApplicationHelper에 포함 도우미 모듈이라고 RailsOverrides에이 코드를 넣습니다. 당신이 원하는 경우 당신은 또한 플러그인 / 보석을 할 수 있습니다.

    하나 잡았다는 당신이 항상 직접 options_for_select 호출해야합니다 이러한 방법을 활용하는 것입니다. 같은 바로 가기

    select("post", "person_id", Person.all.collect {|p| [ p.name, p.id, {"data-stuff"=>"html5"} ] })
    

    이전의 결과를 얻을 것입니다. 대신이 있어야한다 :

    select("post", "person_id", options_for_select(Person.all.collect {|p| [ p.name, p.id, {"data-stuff"=>"html5"} ] }))
    

    다시없는 훌륭한 솔루션,하지만 그것이 아무리 유용한 데이터 속성에 도착하는 가치가있을 수도 있습니다.

  5. ==============================

    5.나뿐만 아니라이 문제에 실행하고이 문제를 해결하기 위해 "enhanced_select"루비 보석을 만들었습니다. 당신은 여기에서 찾을 수 있습니다 :

    나뿐만 아니라이 문제에 실행하고이 문제를 해결하기 위해 "enhanced_select"루비 보석을 만들었습니다. 당신은 여기에서 찾을 수 있습니다 :

    https://github.com/bkuhlmann/enhanced_select

  6. from https://stackoverflow.com/questions/5052889/ruby-on-rails-f-select-options-with-custom-attributes by cc-by-sa and MIT license