0

好的,假设我有一个 post 表和一个 category 表。这是模型的样子:

class User < ActiveRecord::Base    
  acts_as_authentic  
  has_many :posts     

end

而且,这就是帖子模型:

class Post < ActiveRecord::Base
  belongs_to :user
end

这是来自 post 的 new.html.erb:

<% form_for(@post) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.label :views %><br />
    <%= f.text_field :views %>
  </p>            
  <p>
    <%= f.label :category_id %><br />
    <%= f.text_field :category_id %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

我想把category_id改成一个option标签,另外我想把edit.html.erb里面的option循环回,怎么实现呢?谢谢你。

4

1 回答 1

1

您可以使用 collection_select 助手:

f.collection_select(:category_id , Category.all, :id, :name, {:prompt => true})

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M002303

于 2010-07-12T13:56:16.793 回答