Skip to content

Instantly share code, notes, and snippets.

@Humoud
Last active February 18, 2016 08:52
Show Gist options
  • Select an option

  • Save Humoud/3c0759bc13259f3e0800 to your computer and use it in GitHub Desktop.

Select an option

Save Humoud/3c0759bc13259f3e0800 to your computer and use it in GitHub Desktop.
A cheat sheet for making Rails ActiveRecord relations while using some models from the Spree framework.
##########################################################
# Relationship: One-to-One
# Tables: Instructor - Spree::User
# User has one Instructor
##########################################################
# in app/models/instructor.rb
class Instructor < ActiveRecord::Base
belongs_to :spree_user, :class_name => 'Spree::User'
end
# in migration file:
class CreateInstructors < ActiveRecord::Migration
def change
create_table :instructors do |t|
t.string :employee_number
t.belongs_to :spree_user, index: true
t.timestamps null: false
end
end
end
# In app/models/spree/user_decorator.rb
module Spree
User.class_eval do
has_one :instructor
end
end
###
# Accessing via: rails console
##
user = Spree::User.create(email: "[email protected]", password:"123456")
user.save
instructor = Instructor.create(spree_user_id: user.id)
instructor.spree_user # => prints out user fields
##########################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment