Mridang Agarwalla
Mridang Agarwalla

Reputation: 44958

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.

Upvotes: 3

Views: 732

Answers (2)

Chris Kimpton
Chris Kimpton

Reputation: 5541

Thanks to @idlefingers for this:

subject = Subject.find_or_create_by_name("Science")

subject.books.create(:name => "Book A")

Upvotes: 0

Jed Schneider
Jed Schneider

Reputation: 14671

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

Upvotes: 2

Related Questions