2010-12-15 23 views
0

J'utilise une méthode personnalisée select_with_new_option dans ma forme comme ceci:Rails: Comment envelopper le "select" généré avec une balise "div"?

<%= select_with_new_option(f, :shop, :name, :id) %> 

Voici sa définition:

def select_options_with_create_new(objects, text_field, value_field, options={}) 
    object = objects.to_s.singularize 
    all_objects = object.capitalize.constantize.all 
    all_objects = all_objects.sort_by(&options[:order_by]) if options.has_key?(:order_by) 
    select_options = all_objects.map{ |obj| [obj.send(text_field), obj.send(value_field)] } 
    select_options << [wrap_create_new_option("create new #{object}".titleize), "new_#{object}"] 
end 

def wrap_create_new_option(str) 
    ">> #{str} <<" 
end 

# By default, sorts by 'text_field'. 
def select_with_new_option(f, object, text_field, value_field) 
    f.select(:"#{object}_id", select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field), 
      {:prompt => true}, # options 
      {})     # html_options 
end 

Cela crée la balise select et il est option s comme prévu.

Maintenant, je veux envelopper cette select avec un div comme ceci:

<div class='my_class'> 
    <select>...</select> 
</div> 

Quelle serait la meilleure façon de le faire dans « façon Rails »?

Répondre

1

En utilisant la méthode content_tag:

def select_with_new_option(f, object, text_field, value_field) 
    html = f.select(:"#{object}_id", 
      select_options_with_create_new(object.pluralize, text_field, value_field, :order_by => text_field), 
      {:prompt => true}, # options 
      {})     # html_options 
    content_tag :div, html, :class => "my_class" 
end 
3

Si vous ne voulez pas modifier votre méthode, vous pouvez passer à la méthode content_tag comme un bloc:

<%= content_tag :div, :class => "my_class" do %> 
    <%= select_with_new_option(:f, :shop, :name, :id) %> 
<% end %> 
Questions connexes