Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this the best way to go about this or could someone recommend a better approach.

like image 216
Mridang Agarwalla Avatar asked May 20 '26 12:05

Mridang Agarwalla


1 Answers

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

like image 54
Jed Schneider Avatar answered May 23 '26 03:05

Jed Schneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!