将数据插入 Rails
我是 Rails 新手,无法弄清楚如何将数据插入数据库。
我正在读取 CSV 并希望将这些值加载到数据库中。我的模型看起来像这样。
class Book < ActiveRecord::Base
belongs_to :subject
end
class Subject < ActiveRecord::Base
has_many :books
end
...我的数据是这样的:
Science, Book A
Science, Book B
History, Book C
Math, Book D
我用分隔符分割 CSV 行。
如何以这样的方式插入数据:如果主题存在,子图书记录将添加到现有主题,但如果主题不存在,也会创建新主题?
这是解决此问题的最佳方法还是有人可以推荐更好的方法。
I'm new to rails and had trouble figuring out how to insert data into the db.
I'm reading a CSV and would like to load those values into the db. My model looks something like this.
class Book < ActiveRecord::Base
belongs_to :subject
end
class Subject < ActiveRecord::Base
has_many :books
end
...and my data is something like this:
Science, Book A
Science, Book B
History, Book C
Math, Book D
I'm splitting the CSV rows by the delimiter.
How can insert the data in a way that if a subject exists, the child book record will be added to the existing subject but in the event that a subject doesn't exist, a new subject will be created too?
Is this the best way to go about this or could someone recommend a better approach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需重新发明轮子。将标题行添加到 csv 文件中,将其另存为 subject.csv,然后使用内置的固定装置库加载数据: http://api.rubyonrails.org/classes/Fixtures.html
No need to reinvent the wheel. Add a header row to your csv file, save it as subjects.csv and then use the built in fixtures library to load the data: http://api.rubyonrails.org/classes/Fixtures.html
感谢@idlefingers:
Thanks to @idlefingers for this: