我在表单中使用自定义select_with_new_option
方法,如下所示:
<%= select_with_new_option(f, :shop, :name, :id) %>
这是它的定义:
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
这会按预期创建select
代码及其option
。
现在,我想将select
与div
这样包裹起来:
<div class='my_class'>
<select>...</select>
</div>
在&#34; Rails方式&#34;中最简单的方法是什么? ?
答案 0 :(得分:3)
如果您不想修改方法,可以将其作为块传递给content_tag方法:
<%= content_tag :div, :class => "my_class" do %>
<%= select_with_new_option(:f, :shop, :name, :id) %>
<% end %>
答案 1 :(得分:1)
使用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