Rails数据库关联/迁移 [英] Rails Database Association / Migration

查看:105
本文介绍了Rails数据库关联/迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Rails,并试图找出数据库关联.如果我有一个数据库表,上面有说用户"的ID,名称,电子邮件等,还有一个消息"表,上面有消息,发件人(用户)和收件人(也是用户),该如何设置迁移和楷模.在这里,我正在使用Rails 3.1.我很确定我可以仅使用Message表中的一个User(在迁移中使用references:User)来做到这一点,但是我不确定如何设置其中两个.

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.

推荐答案

一些入门资源: RoR指南:迁移

首先进行用户迁移

$ rails generate model User name:string email:string

然后迁移您的邮件

$ rails generate model Message message:string user_id:integer

然后在您的消息模型(/app/models/messages.rb)

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

belongs_to :user

在您的用户模型中(/app/models/users.rb)

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!

这篇关于Rails数据库关联/迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆