我有一个User
模型和一个Question
model.
我想添加一个belongs_to :user
关联到Question
模型,但我希望将该关联称为author
。例如,我会打电话question.author
而不是question.user
.
显然这需要两个步骤:
- models/question.rb 中的关联
- 迁移(注意用户表和问题表都已存在)
令人惊讶的是,我没有在 Rails 5 的不同答案中找到执行此操作的单一常规方法。
我该怎么做呢?
rails g migration add_user_to_questions user:references
rails db:migrate
理想情况下,您还可以打开生成的迁移并更改add_reference
通过添加您需要的选项。更“完整”的 add_reference 示例:
add_references(
:user,
null: false,
index: {name: "custom_index_name_if_needed"},
type: :integer,
foreign_key: {
to_table: "public.my_users_table",
on_delete: :cascade # ensure the row is deleted when user is deleted from DB
}
)
然后在模型中:
class Question < ApplicationRecord # or ActiveRecord::Base
belongs_to :author, class_name: 'User', foreign_key: :user_id
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)