Ruby on Rails:为什么选择框不显示当前对象值?
以下是来自views/products/edit.html.erb
的相关代码:
{:action => 'update', :id => @product.id}) do |f| %> "form", :locals => {:f => f}) %>
来自views/products/_form.html.erb
:
从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 <> #{str} < text_field)) end
我希望默认情况下选择框为@product.shop_id
,但这不是真的(第一个选项始终是默认值)。
我错过了什么?
好吧,我明白了。 只需在select_options_with_create_new
方法中删除options_for_select(select_options)
。
options_for_select
将2-d数组select_options
成一个html选项字符串,但是, select
表单帮助程序可以接受它,但不指定selected
属性。 只需将2-d数组作为第二个参数传递给select
方法,它就会自动分配selected
数组。
我认为,在这种情况下,您需要做的就是确保在edit
操作中设置@product
:
def edit @product = Product.find(params[:id]) end
然后改变你的第一行:
<%= form_for(:product, :url => {:action => 'update', :id => @product.id}) do |f| %>
至
<%= form_for(@product, :url => {:action => 'update', :id => @product.id}) do |f| %>
第一个代码块肯定会更新正确的产品,但是如果生成一个form_for @product
,并且设置了@product
变量,您将只看到反映的当前值。