2012-12-04 53 views
0

我有這2種型號:如何在以下(簡單)情況下使用collection_select?

class Person < ActiveRecord::Base 
    attr_accessible :contact, :name 

    validates :name, :presence => true 

    has_many :books 

end 

class Register < ActiveRecord::Base 
    attr_accessible :checkin, :checkout, :notes, :person, :book 

end 

在寄存器/ _form.html.erb我想用f.collection_select在那裏我可以從列表中選擇一個人的名字。註冊模型的目的是記錄結賬的歷史記錄。

這是我第一次嘗試使用collection_select,並且我無法用我在stackoverflow和google上閱讀的示例來包裝頭部。也許我沒有模型中需要的所有東西?

請幫忙。

回答

0

您的模型在關聯方面存在錯誤。正確的協會應該是:

class Person < ActiveRecord::Base 
    has_many :registers, :inverse_of => :person 
end 

class Register < ActiveRecord::Base 
    belongs_to :person, :inverse_of => :registers 
end 

然後在你的registers/_form.html.erb你必須有類似以下內容:

<%= form_for :register do |f| %> 
    <% # ... input elements for the rest of the Register model %> 

    <%= f.collection_select :person_id, Person.all, :id, :name %> 

    <% # ... input elements for the rest of the Register model %> 

    <%= f.submit %> 
<% end %> 
+0

謝謝。當我將這些行粘貼到我的代碼中時,我在'http:// localhost:3000/registers/new'頁面上爲#'定義了'undefined method'person_id'。我錯過了什麼嗎? – webmagnets

+0

你的列在'registers'上被稱爲'person_id'嗎?它怎麼叫? –

+0

我不明白這個問題。我是一個noob。你的意思是我需要一個名爲person_id的外鍵在註冊表中嗎? – webmagnets

相關問題