Ruby on Rails:为什么选择框不显示当前对象值?

时间:2010-12-14 05:48:33

标签: ruby-on-rails forms select 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 %>

来自views/products/_form.html.erb

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

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

我希望默认情况下选择框为@product.shop_id,但这不是真的(第一个选项始终是默认值)。

我错过了什么?

2 个答案:

答案 0 :(得分:7)

好吧,我明白了。只需在options_for_select(select_options)方法中删除select_options_with_create_new

options_for_select将2-d数组select_options组合成一个html选项字符串,select表单帮助程序接受该字符串,但是不指定selected属性。只需将2-d数组作为第二个参数传递给select方法,它就会自动分配selected

答案 1 :(得分:0)

我认为,在这种情况下,您需要做的就是确保在@product操作中设置edit

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变量,则只能看到反映的当前值。