Skip to content

Instantly share code, notes, and snippets.

@bobisme
Created May 3, 2018 00:12
Show Gist options
  • Save bobisme/bbf5a3aa8a62225ce5eaaf0e76f268fd to your computer and use it in GitHub Desktop.
Save bobisme/bbf5a3aa8a62225ce5eaaf0e76f268fd to your computer and use it in GitHub Desktop.
rails relationship model
class CreateCats < ActiveRecord::Migration[5.0]
def change
create_table :cats do |t|
t.string :name
t.timestamps
end
end
end
class CatRelationship < ActiveRecord::Migration[5.0]
def change
create_table :cat_relationships do |t|
t.references :giver, references: :cat, foreign_key: true
t.references :taker, references: :cat, foreign_key: true
end
end
end
class CatRelationship < ApplicationRecord
def self.relationship_exists?(giver:, taker:)
where(giver_id: giver, taker_id: taker).exists?
end
end
irb(main):001:0> ezzie = Cat.create(name: 'ezzie'); beans = Cat.create!(name: 'beans')
=> #<Cat id: 4, name: "beans", created_at: "2018-05-03 00:09:35", updated_at: "2018-05-03 00:09:35">
irb(main):002:0> CatRelationship.create!(giver_id: ezzie.id, taker_id: beans.id)
=> #<CatRelationship id: 3, giver_id: 3, taker_id: 4>
irb(main):003:0> CatRelationship.relationship_exists?(giver: ezzie, taker: beans)
CatRelationship Exists (0.3ms) SELECT 1 AS one FROM "cat_relationships" WHERE "cat_relationships"."giver_id" = 3 AND "cat_relationships"."taker_id" = 4 LIMIT ? [["LIMIT", 1]]
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment