仍在插入我的第一个 Rails 程序(Ruby 2.0、Rails 4.0)。主模型“联系人”应在“颜色”表的表单中包含一个下拉列表。我已经添加了颜色模型,创建了 html 下拉菜单,并尝试为颜色模型播种(下拉菜单当前显示一个空菜单)。我从两个数组填充 seeds.rb 中的颜色,并验证两个数组都充满字符串值(与相应颜色迁移列的值相同)。当我尝试将数组值放入颜色表时,它会创建正确数量的条目(每个数组的大小为 140 个元素),但两列中的所有条目均为 nil。
下面是我的种子.rb
额外的菜鸟问题?如何将代码粘贴到 Linux 计算机上的 Stackoverflow 中而不是键入代码?
colors = Array.new
colors = File.readlines("db/seeds/colornames.csv").map! {|name| name.chomp}
hexes = Array.new
hexes = File.readlines("db/seeds/colorhexes.csv").map! {|hex| hex.chomp}
Color.delete_all #because I keep having to reseed
x = 0
colors.each do |color|
Color.create!(:name => color, :hex => hexes[x])
x+=1
end
和 contact.rb
class Contact < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :zip_code, :favorite_color, :color_id #I have brought in the right gem to use this older method
belongs_to :color
#validation of fields other than :favorite_color in here. Nothing pertinent to this q
#favorite color validation
validates_presence_of :favorite_color
end
和颜色.rb
class Color < ActiveRecord::Base
has_many :contacts
end
最佳答案
你安装了这个 gem github.com/rails/protected_attributes 吗?如果这是真的,那么您需要像 Rails 3 中一样将这一行添加到您的模型中:
attr_accessible :name, :hex
关于ruby-on-rails - Rails 表只会播种 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19345795/