2010-12-14 56 views
3

這裏是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默認,但這是不正確的(第一個選項總是默認值)。

我錯過了什麼?

回答

7

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

options_for_select 2-d陣列select_options組裝成的HTML選項的字符串,它是由select形式助手接受,但是,如果沒有分配selected屬性。只需將二維數組作爲第二個參數傳遞給select方法,它將自動分配selected

+0

你太棒了!它解決了這個問題。非常感謝!!! – 2010-12-14 11:54:38

0

我認爲,在這種情況下,所有你需要做的是確保你在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| %> 

第一個代碼塊肯定會更新正確的產品,但是y只有當您生成form_for @product時,纔會看到反映的當前值,該變量集爲@product

+0

我在'edit'方法中設置了'@ product',就像你寫的一樣。我也嘗試將':product'更改爲'@ product',但它沒有幫助。你有什麼其他的想法可能是錯的? – 2010-12-14 07:21:07

+0

是@ product.id和obj.send(value_field)的相同類型嗎?如果其中一個是整數,而另一個是可能導致您遇到問題的字符串。另外需要注意的是,如果刷新頁面並且選擇框中當前選定的選項發生更改,則某些瀏覽器不顯示更改,因此測試這些更改可能具有欺騙性。 – Iain 2010-12-14 07:52:07

+0

@lain:'@ product.id'是整數。 'obj.send(value_field)'是'shop.send(:id)'在我的情況下,相當於'shop.id',它也是整數。我相信瀏覽器不是這裏的問題。我使用最新的Firefox。 – 2010-12-14 09:24:14