Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在我的 Ruby on Rails 3 应用程序中使用了 Devise Ruby gem。当登录用户创建我的一个模型时,我想将他们的用户 ID 保存为创建它的人。我该怎么办?
integer创建一个具有名为的列的迁移文件user_id,这是存储关联的位置。(有关如何执行此操作的详细信息,请参阅迁移指南)。
integer
user_id
在您的模型中,添加:(有关更多详细信息,belongs_to :user请参阅关联指南)
belongs_to :user
在模型的控制器中,添加@your_model.user = current_user创建操作。这将完成您正在寻找的关联。(current_user是 devise 提供的一种方法,它返回当前登录用户的用户 ActiveRecord)
@your_model.user = current_user
current_user
注意:进行实际关联的方法不止一种。我建议在控制器中进行,但可以在模型或其他地方进行。