andrefurquin
andrefurquin

Reputation: 522

Creating objects with relationship in Rails console

I've got a Rails project to do. I'm parsing an .xls file using roo and putting the information in a relational database. How can I get this relationship back if ruby does not use foreign keys ? Suppose I got the Category and Subcategory table, I'm reading the line in the .xls file and writing the information to the database. A category has many subcategories. But there may be an existing category (so I don't need to add it again). Using rails console how would I do it ? I'm using something like a = Category.new(name_category: "test"). That should create a category but it's not linked to a subcategory. How would I add and link them together in one command ? What if a subcategory has an item. How would I create something involving 3 relationships ?

Upvotes: 2

Views: 3524

Answers (1)

ndbroadbent
ndbroadbent

Reputation: 13803

Don't do it in one command. You would need to 'find or create' the Category first.

category = Category.find_or_create_by_name(name: "test")
Subcategory.create(name: "foo", category: category)

Your models should look like:

class Category < ActiveRecord::Base
  has_many :subcategories
end

class Subcategory < ActiveRecord::Base
  belongs_to :category
end

Upvotes: 1

Related Questions