Inserting Data into Rails
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 thi开发者_如何学Pythons the best way to go about this or could someone recommend a better approach.
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
Thanks to @idlefingers for this:
subject = Subject.find_or_create_by_name("Science")
subject.books.create(:name => "Book A")
精彩评论