0

我有这两个模型:

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

在 registers/_form.html.erb 我想使用 f.collection_select 我可以从列表中选择一个人的名字。Register 模型的目的是记录结帐的历史。

这是我第一次尝试使用 collection_select,我无法用我在 stackoverflow 和 google 上阅读的示例来解决这个问题。也许我没有模型中需要的所有东西?

请帮忙。

4

1 回答 1

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 %>
于 2012-12-04T13:34:59.280 回答