简体   繁体   中英

Rails: How to wrap the generated “select” with a “div” tag?

I use a custom select_with_new_option method in my form like this:

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

Here is it's definition:

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

This creates the select tag and it's option s as expected.

Now, I want to wrap this select with a div like this:

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

What would be the easiest way to do this in "Rails way" ?

If you don't want to modify your method, you can pass it to the content_tag method as a block:

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

Using the content_tag method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM