Rails 3:如何将数组播种到seed.rb?

js1*_*111 0 activerecord ruby-on-rails

我有一个interests只有:name属性的表.

我正试图播种(通过seed.rb)以下数组,以便它们都以我的形式显示(复选框)......我该怎么做?

有没有比存储它更好的方法seed.rb

[ "Adventure Sports", "Arts and Crafts", "Beauty/Hair", 
  "Books", "Dining Out", "Fine Art", "Fine Jewelry", 
  "Gardening", "Golf" ]
Run Code Online (Sandbox Code Playgroud)

pdu*_*ler 5

如果你想把它放到你的seed.rb中,你可以像在其他地方一样创建它们,例如

[ "Adventure Sports", "Arts and Crafts"].each do |interest|
  Interest.create!({:name => interest})
end
Run Code Online (Sandbox Code Playgroud)

或者,您可以将它们作为常量存储在模型中,并在表单中使用它.

class Interest < ActiveRecord::Base
  INTERESTS = [ "Adventure Sports", "Arts and Crafts" ]
end
Run Code Online (Sandbox Code Playgroud)

然后以你的形式,例如:

f.select Interest::INTERESTS
Run Code Online (Sandbox Code Playgroud)