Rails Database Association / Migration

回眸只為那壹抹淺笑 提交于 2019-12-11 13:36:55

问题


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.


回答1:


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!




回答2:


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"


来源:https://stackoverflow.com/questions/8549167/rails-database-association-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!