2011-06-24 60 views
1

試圖將表單中的數據保存到數據庫。 使用select_tag從select_tag保存數據

<%= select_tag :size, options_from_collection_for_select(@plan, 'name', 'size') %> 

一切都很好,它抓住規模和電子郵件,但是當我嘗試將數據從形式(大小)存儲,它傳遞NULL。

這裏是我的控制檯:

Started POST "/users" for 127.0.0.1 at 2011-06-24 07:25:29 -0500 
Processing by UserController#create as HTML 
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MfT3gs5TtR+bvpaLro0E8Qm1zojaY2ms9WK0WprKPAw=", "size"=>"small", 
"user"=>{"email"=>"[email protected]"}, "commit"=>"Create User"} 
AREL (0.4ms) INSERT INTO "users" ("email", "size", "created_at", "updated_at") VALUES 
('[email protected]', NULL, '2011-06-24 12:25:29.646814', '2011-06-24 12:25:29.646814') 
Redirected to http://localhost:3000/users/14 
Completed 302 Found in 56ms 

所以,它從形式得到正確的數據,當你看到「大小」 =>「小」,但是當它的時間來存放它,它並將其作爲NULL,

VALUES ('[email protected]', NULL, '2011-06-24 

我想,這是select_tag,因爲它具有u連接的犯規,因爲text_field確實

<%= form_for @user do |u| %> 
        <%= render 'shared/error_messages' %> 
         <p><%= u.label :size, 'How many employees do you have?' %>: </p> 
         <p><%= select_tag :size, options_from_collection_for_select(@plan, 'name', 'size') %></p> 

         <p><%= u.label :email, 'What\'s your email address?' %>:</p> 
         <p><%= u.text_field :email %></p> 
         <%= u.submit%> 
        <% end %> 

但瓦特母雞我試過u.select_tag =錯誤,未定義的方法。

我的模型

class User < ActiveRecord::Base 
attr_accessible :size, :email 
end 

有什麼想法?

回答

1

您需要在「users」哈希中嵌入「size」參數。當您在日誌中查找要驗證看到這樣的事情:

"user"=>{"email"=>"[email protected]", "size"=>"small"} 

要實現的表單的裏面的,你可以保持你現有的select_tag和範圍它是這樣:

<%= select_tag 'user[size]', options_from_collection_for_select(@plan, 'name', 'size') %> 

或者你對於這種情況,它看起來像你可以使用範圍對錶單對象collection_select範圍:

<%= u.collection_select :size, @plan, :name, :size %> 
+0

它的工作,謝謝亞倫 – RedRory