Mis*_*hko 3 forms select ruby-on-rails ruby-on-rails-3
以下是相关代码views/products/edit.html.erb
:
<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<%= submit_tag("Update Product") %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
来自views/products/_form.html.erb
:
<%= select_with_new_option(f, :shop, :name, :id) %>
Run Code Online (Sandbox Code Playgroud)
来自helpers/products_helper.rb
:
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}"]
options_for_select(select_options)
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))
end
Run Code Online (Sandbox Code Playgroud)
我希望@product.shop_id
默认选择框,但这不是真的(第一个选项始终是默认值).
我错过了什么?
好吧,我明白了.只需options_for_select(select_options)
在select_options_with_create_new
方法中删除即可.
将options_for_select
2-d数组select_options
合成一个html选项字符串,然后由select
表单助手接受,但不分配selected
属性.只需将二维数组select
作为第二个参数传递给方法,它就会selected
自动分配.