bytebiscuit
bytebiscuit

Reputation: 3496

Model associations in RoR

I'm trying to understand how rails works in respect to foreign key and primary keys. Coming from a pure SQL background the Rails method seems very alien to me. I have the following two migrations:

Groups

class CreateGroups < ActiveRecord::Migration
  def self.up
    create_table :groups do |t|
      t.string :title
      t.text :description
      t.string :city
      t.integer :event_id
      t.string :zip
      t.string :group_id
      t.text :topics
      t.timestamps
    end
  end

  def self.down
    drop_table :groups
  end
end

and Events:

class CreateEvents < ActiveRecord::Migration
  def self.up
    create_table :events do |t|
      t.string :title
      t.string :description
      t.string :city
      t.string :address
      t.time :time_t
      t.date :date_t
      t.string :group_id
      t.timestamps
    end
  end

  def self.down
    drop_table :events
  end
end

A Group can have many events and an event can belong to a single group. I have the following two models:

class Event < ActiveRecord::Base
 belongs_to :group, :foreign_key => 'group_id'

end

and

 class Group < ActiveRecord::Base
 attr_accessible :title, :description, :city, :zip, :group_id, :topics
 has_many :events
end

not sure how to specify foreign keys and primary keys to this. For example a group is identified by the :group_id column and using that I need to fetch events that belong to a single group! how do i do this!

Upvotes: 1

Views: 102

Answers (1)

DGM
DGM

Reputation: 26979

I see you have group_id and event_id as strings in your migration, so I think you might be missing a rails convention. The rails convention is that all tables have a primary key named id of type integer, and any foreign keys reference it by the name of the model, singular, + _id:

table groups:
   id:  integer
   name:   string


table events:
   id:  integer
   name:  string
   group_id:  integer

From this convention, all you have to specify in your models is:

class Event < ActiveRecord::Base
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_many :events
end

At this point, rails knows what to do by convention over configuration: To find an event's group, it knows to look for group_id (singular) to refer to groups.id (plural table name)

event = Event.first  #=> returns the first event in database
group = event.group  #=> returns the group object 

Similarly, it know how to find all the events in a group

group = Group.first  #=> returns first group in database
group.events         #=> returns an Enumerable of all the events

For more reading, read the rails guide on associations

Upvotes: 2

Related Questions