2012-01-27 69 views
0

我想學習軌道上的紅寶石,寫我自己的簡單的應用程序(待辦事項列表)。我現在想添加一個下拉菜單來選擇一個用戶來分配任務。collection_select和保存在軌道上的紅寶石的記錄

我schema.rb:現在

create_table "items", :force => true do |t| 
t.text  "description" 
t.string "priority" 
t.date  "date" 
t.time  "time" 
t.datetime "created_at" 
t.datetime "updated_at" 
t.boolean "done" 
t.string "name" 
end 

create_table "users", :force => true do |t| 
t.string "name" 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

,在我的形式我有一個字段:

<%= f.collection_select(:user, User.all, :id, :name) %> 

它儘可能的工作作爲展示我的用戶不用。但是,當我嘗試保存時,我當然得到:我已經建立了關係(用戶有很多任務,任務有一個用戶)。我錯過了什麼? 非常感謝您的幫助!

回答

0

'items'表中沒有'user_id'列。

rails g migration AddUserToItems user_id:integer 
rake db:migrate 

class Item 
    belongs_to :user 
    ... 
end 

class User 
    has_many :items 
    ... 
end 

collection_select(:item, :user_id, User.all, :id, :name) 
+0

好吧讓我試試,同時我通過使用下面的代碼得到它的工作: <%= f.collection_select(:name,User.all,:name,:name)%> – alemur 2012-01-27 01:09:57

+0

try:collection_select :item,:user_id,User.all,:id,:name)。 http://guides.rubyonrails.org/form_helpers.html – 2012-01-27 01:33:21

0
<%= collection_select(:item, :user_id, User.all, :id, :name, {:prompt=>true}) %> 
         1.  2.  3.   4. 5.  6. 
  1. 模型

  2. 如果你是存儲在模型

  3. 收集用戶的

  4. 什麼都會被保存

  5. 所顯示

  6. 提示爲 「請選擇」

這可能會有幫助。