代码之家  ›  专栏  ›  技术社区  ›  jalagrange

Rails助手“集合选择”

  •  3
  • jalagrange  · 技术社区  · 16 年前

    我的问题和你的完全一样 this guy

    我需要帮助 试图输出这样的东西

    <select name="user[university_id]" id="user_university_id" class="selectable">
    <option value="1" title="uni1">Uni1</option>
    <option value="2" title="uni2">Uni2</option>
    </select>
    

    助手似乎从未输出 这对这个插件很重要

    请帮忙,提前谢谢

    编辑:我当前的rails代码是

    <%= f.collection_select(:university_id,University.all,:id,:name)%
    

    <select name="user[university_id]" id="user_university_id">
            <option value="1">Uni1</option>
            <option value="2">Uni2</option>
        </select>
    

    所以基本上我需要的是 选项。

    2 回复  |  直到 9 年前
        1
  •  2
  •   Geoff Lanotte    16 年前

    你有没有想过让你自己的助手滚蛋?我刚把这段代码从 rails source 然后改了名字加了标题。

      def options_for_select_with_title(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|
          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 title="#{html_escape(value.to_s.downcase)}" value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}>#{html_escape(text.to_s)}</option>)
        end
    
        options_for_select.join("\n").html_safe
      end
    
        2
  •  0
  •   HurnsMobile    16 年前

    $('#user_university_id option').each( function(){
        var optText = $(this).html();
        $(this).attr('title', optText);
    })
    

    这将为标题分配选项的文本内容。或者,您可以使用生成的ID执行更随意的操作。