這裏是views/products/edit.html.erb
相關代碼:Ruby on Rails:爲什麼選擇框不顯示當前對象值?
<%= 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
默認,但這是不正確的(第一個選項總是默認值)。
我錯過了什麼?
你太棒了!它解決了這個問題。非常感謝!!! – 2010-12-14 11:54:38