2012-12-04 49 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

相关问题