如何在数据库中反映

如何在数据库中反映

本文介绍了如何在数据库中反映 Ruby on Rails 中新的belongs_to 和has_many 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手(通常是 Python 专家),我一直在尝试构建一个简单的任务管理器应用程序以获取乐趣.我正在使用 Devise 进行身份验证,并且有一个我试图与用户关联的 Task 对象.我已将以下内容添加到任务模型中:

I am new to rails (usually a python guy) and have just been trying to build a simple task manager application for fun. I am using Devise for authentication and have a single Task object I am trying to relate to a user. I have added the following to the Task model:

class Task < ActiveRecord::Base
    belongs_to :user
end

并且我在我的 Devise 用户模型中添加了以下内容:

and I have added the following in my User model for Devise:

class User < ActiveRecord::Base
   has_many :tasks

   <<normal Devise stuff>>
end

每当我添加此信息时,我都会运行:rake db:migrate.然后它给了我一个错误,当我尝试对它做任何事情时,user_id 的数据库字段不存在.

Whenever I added this information I then ran: rake db:migrate. It then gave me an error that the database field did not exist for user_id when I tried to do anything with it.

我确信我遗漏了一些相当简单的东西.感谢您的帮助.

I am sure it is something rather simple that I am missing. Thanks for the help.

推荐答案

向模型添加 belongs_to(或任何其他)关系只会告诉活动记录模型是逻辑链接的.这使您可以访问诸如 task.user 之类的方法.要使其真正起作用,必须通过数据库字段链接实例.

Adding a belongs_to (or any other) relationship to your model only tells active record that models are linked logically. This gives you access to methods like task.user. For this to actually work, the instances must be linked via database fields.

这是您遗漏的步骤:您需要创建一个迁移,该迁移将向 Task 表中添加一列,指示它属于哪个用户.

This is the step you're missing: you need to create a migration that will add a column to the Task table indicating which user it belongs to.

rails g migration AddUserIdToTasks user_id:integer

注意 AddUserIdToTasks 可以是您想要的任何名称.没什么区别.然后您可以打开 db/migrations/add_user_to_tasks 并查看它的作用.通常 self.up 会按照你想要的方式修改数据库,而 self.down 会做相反的事情(因此,在这种情况下,删除 used_id).

Note AddUserIdToTasks can be whatever name you want. It makes no difference. You can then open db/migrations/add_user_to_tasks and see what it does. Usually self.up will modify the database how you want it and self.down will do the opposite (so, in this case, remove the used_id).

然后实际执行 SQL 命令来改变数据库表和模式,运行

Then to actually execute the SQL commands to alter the database table and schema, run

rake db:migrate

这篇关于如何在数据库中反映 Ruby on Rails 中新的belongs_to 和has_many 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:46