简体   繁体   中英

Rails 3: How to seed an array to a seed.rb?

I have an interests table that only has a :name attribute.

I'm trying to seed (via seed.rb ) the following array so that they all display in my form (checkbox)... How would I do that?

Is there a better way than storing this in seed.rb ?

[ "Adventure Sports", "Arts and Crafts", "Beauty/Hair", 
  "Books", "Dining Out", "Fine Art", "Fine Jewelry", 
  "Gardening", "Golf" ]

If you want to put it into your seed.rb, you create them like you would elsewhere, eg

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

Alternatively, you could store them in your Model as a constant and use that in your form.

class Interest < ActiveRecord::Base
  INTERESTS = [ "Adventure Sports", "Arts and Crafts" ]
end

And then in your form eg:

f.select Interest::INTERESTS

I'm using find_or_create_by_... to ensure that records are only created once even if the seeds.rb is run again:

[ "Adventure Sports", "Arts and Crafts"].each do |interest|
  Interest.find_or_create_by_name(interest)
end

With name being the column name. If column name is eg title use find_or_create_by_title .

It can also be used to set more than one column eg:

[["Adam", 10], ["Allan", 20], ["Andy", 30]].each do |data|
  role = Role.find_by_name("editor").id
  User.find_or_create_by_name_and_credits_and_role_id(data[0], data[1], role)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM