Skip to content

Instantly share code, notes, and snippets.

@bzitzow
Last active December 25, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bzitzow/7035572 to your computer and use it in GitHub Desktop.
Save bzitzow/7035572 to your computer and use it in GitHub Desktop.
class CategoriesUnitsTable < ActiveRecord::Migration
def self.up
create_table :categories_units, :id => false do |t|
t.references :category
t.references :unit
end
add_index :categories_units, [:category_id, :unit_id]
end
def self.down
drop_table :categories_units
end
end
# == Schema Information
#
# Table name: categories
#
# id :integer not null, primary key
# title :string(255)
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_updated_at :datetime
#
class Category < ActiveRecord::Base
has_and_belongs_to_many :units
has_attached_file :image, :styles => { :medium => "275x55>" }
end
# Truncated result set for clarity
Unit.all.includes(:categories)
<Unit id: 8, code: 1, title: "asdfasfd", phone: "33333333", active: true, category_id: nil>]>
## Raw:
Unit.all.includes(:categories)
Unit Load (35.9ms) SELECT "units".* FROM "units"
SQL (0.4ms) SELECT "categories".*, "t0"."unit_id" AS ar_association_key_name FROM "categories" INNER JOIN "categories_units" "t0" ON "categories"."id" = "t0"."category_id" WHERE "t0"."unit_id" IN (1, 2, 3, 5, 7, 8)
=> #<ActiveRecord::Relation [#<Unit id: 1, code: 1234, title: "Store Name Here", phone: "(916) 367 9977", active: true, category_id: nil>, #<Unit id: 2, code: 123, title: "Unit Test", phone: "11231421345", active: true, category_id: nil>, #<Unit id: 3, code: 123414, title: "test", phone: "11231421345", active: false, category_id: nil>, #<Unit id: 5, code: nil, title: "asdgasdfg", phone: "", active: true, category_id: nil>, #<Unit id: 7, code: nil, title: "asdfas", phone: "222222222", active: true, category_id: nil>, #<Unit id: 8, code: 1, title: "asdfasfd", phone: "33333333", active: true, category_id: nil>]>
# == Schema Information
#
# Table name: units
#
# id :integer not null, primary key
# code :integer
# title :string(255)
# phone :string(255)
# active :boolean
# category_id :integer
#
class Unit < ActiveRecord::Base
has_and_belongs_to_many :categories, :join_table => :categories_units
accepts_nested_attributes_for :categories
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment