views:

21

answers:

1

I'm a bit new to rails so if this is very basic please bear with me.

I am creating something like a chat application. My model looks like this (from schema.rb)

create_table "people", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "session_id"
end

create_table "sessions", :force => true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "leader_id"
end

I've set up the basic relationship I want -- which is session_id is a foreign key in the people table as such:

class Person < ActiveRecord::Base
belongs_to :session
end

class Session < ActiveRecord::Base
has_many :people
end

I want the leader_id to now be the person who is the "host" of the session (therefore its a foreign key to exactly one person). How do I setup an additional association so I can do:

session = Session.find_by_id(1)
host = Person.new(:name => 'joebob')
session.leader = host
+1  A: 

You can tell Rails that the leader_id is really a Person id by specifying the class name in the belongs_to association:

class Session < ActiveRecord::Base
  belongs_to :leader, :class_name => "Person"
end
yjerem
Wow worked like a charm. Thanks!!! I guess belongs_to always means 'add a foreign key to this model'
Ish