Skip to content

Instantly share code, notes, and snippets.

@nickhoffman
Created June 8, 2011 14:30
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 nickhoffman/1014525 to your computer and use it in GitHub Desktop.
Save nickhoffman/1014525 to your computer and use it in GitHub Desktop.
pcalendar joins stuff
rails g scaffold user name:string
rails g scaffold prediction title:string
rails g scaffold position believes_it:boolean
rails g migration position_belongs_to_user
#class PositionBelongsToUser < ActiveRecord::Migration
# def self.up
# add_column :positions, :user_id, :integer
# end
#
# def self.down
# remove_column :positions, :user_id
# end
#end
rails g migration position_belongs_to_prediction
#class PositionBelongsToPrediction < ActiveRecord::Migration
# def self.up
# add_column :positions, :prediction_id, :integer
# end
#
# def self.down
# remove_column :positions, :prediction_id
# end
#end
rake db:migrate
ActiveRecord::Base.logger = Logger.new STDOUT
sully = User.create :name => 'Sully'
nick = User.create :name => 'Nick'
pred1 = Prediction.create :title => 'something'
pred2 = Prediction.create :title => 'else'
# Sully and Nick believe in opposite predictions.
sully_pos1 = Position.create :believes_it => false, :user => sully, :prediction => pred1
sully_pos2 = Position.create :believes_it => true, :user => sully, :prediction => pred2
nick_pos1 = Position.create :believes_it => true, :user => nick, :prediction => pred1
nick_pos2 = Position.create :believes_it => false, :user => nick, :prediction => pred2
# Users who believe pred1.
User.joins(:positions).where('positions.believes_it' => true, 'positions.prediction_id' => pred1.id).to_a
class Position < ActiveRecord::Base
belongs_to :user
belongs_to :prediction
end
class Prediction < ActiveRecord::Base
has_many :positions
has_many :users, :through => :positions
end
class User < ActiveRecord::Base
has_many :positions
has_many :predictions, :through => :positions
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment