Skip to content

Instantly share code, notes, and snippets.

@jgautsch
Created March 13, 2013 20:58
Show Gist options
  • Save jgautsch/5156100 to your computer and use it in GitHub Desktop.
Save jgautsch/5156100 to your computer and use it in GitHub Desktop.
Models and associations
class User < ActiveRecord::Base
.
. # ... = stuff irrelevant to the problem
.
has_one :schedule
.
.
.
end
class Schedule < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :schedule
attr_accessible :end_time, :start_time, :type
end
#
# Now the problem on the command line:
#
Loading development environment (Rails 3.2.12)
1.9.3p374 :001 > @user = User.find(2)
User Load (4.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
=> #<User id: 2, email: "pcp1@example.com", encrypted_password: "$2a$10$HFABajl6ZB/Ryt.CoFezz.l6ejQHbYqmEu7GyHDUjNjU...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2013-03-13 05:28:33", updated_at: "2013-03-13 05:28:33", name: "Bob Johnson", customer_id: nil, last_4_digits: nil>
1.9.3p374 :002 > @user.schedule
Schedule Load (0.1ms) SELECT "schedules".* FROM "schedules" WHERE "schedules"."user_id" = 2 LIMIT 1
=> #<Schedule id: 1, user_id: 2, created_at: "2013-03-13 05:30:26", updated_at: "2013-03-13 05:30:26">
1.9.3p374 :003 > Appointment.all
Appointment Load (0.1ms) SELECT "appointments".* FROM "appointments"
=> [#<Appointment id: 1, appt_type: "test", start_time: "2013-03-14 16:19:00", end_time: "2013-03-14 17:19:00", schedule_id: nil, created_at: "2013-03-13 20:44:17", updated_at: "2013-03-13 20:44:17", filled: nil>]
1.9.3p374 :004 > @appointment = Appointment.first
Appointment Load (0.2ms) SELECT "appointments".* FROM "appointments" LIMIT 1
=> #<Appointment id: 1, appt_type: "test", start_time: "2013-03-14 16:19:00", end_time: "2013-03-14 17:19:00", schedule_id: nil, created_at: "2013-03-13 20:44:17", updated_at: "2013-03-13 20:44:17", filled: nil>
1.9.3p374 :005 > @appointment
=> #<Appointment id: 1, appt_type: "test", start_time: "2013-03-14 16:19:00", end_time: "2013-03-14 17:19:00", schedule_id: nil, created_at: "2013-03-13 20:44:17", updated_at: "2013-03-13 20:44:17", filled: nil>
1.9.3p374 :006 > @appointment.schedule_id = @user.schedule.id
=> 1
1.9.3p374 :007 > @user.schedule.appointments
Appointment Load (0.2ms) SELECT "appointments".* FROM "appointments" WHERE "appointments"."schedule_id" = 1
=> []
1.9.3p374 :008 > @appointment.id
=> 1
1.9.3p374 :009 > @appointment.schedule_id
=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment