slabounty
slabounty

Reputation: 704

Rails Database Association / Migration

I'm learning rails and I'm trying to figure out database associations. If I have a database table with say Users that has an id, name, email, etc. and a Message table with the message, a sender (User) and recipient (also a User), how do I set up the migration and the models. Here, I'm using Rails 3.1. I'm pretty sure I can do it with just one User in the Message table with the references:User in the migration, but I'm not sure how to set up two of them.

Upvotes: 1

Views: 2512

Answers (2)

slabounty
slabounty

Reputation: 704

OK, here's what I ended up with.

First the migration ...

class CreateMessage < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.string :greeting
      t.integer :sender_id
      t.integer :recipient_id

      t.timestamps
    end
  end
end

Next in the Message model ...

# Message model
belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_id"

and in the User model ...

# Message model
belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_id"

Upvotes: 0

Matt McClure
Matt McClure

Reputation: 2156

Some resources to get you started: Rails Tutorial: User Model RoR Guides: Migrations

First make your user migration

$ rails generate model User name:string email:string

Then your messages migration

$ rails generate model Message message:string user_id:integer

Then in your Messages model (/app/models/messages.rb)

belongs_to :user

And in your User model (/app/models/users.rb)

has_many :microposts

Obviously this is a rough sketch of what needs to happen, but that should get you started!

Upvotes: 7

Related Questions