我有一个Rails API,目前有两个模型,HelpCategory
和HelpRequest
。
HelpRequest
的每个实例只能与HelpCategory
的一个实例相关。HelpCategory
的每个实例可以与HelpRequest
的许多实例相关。
[创建HelpRequest
的新实例时,我希望能够将HelpCategory
的实例的ID添加到HelpRequest
。
例如,我希望能够做这样的事情。
HelpCategory.create!(title: "Help with Shopping")
# {id: 1, title: "Help with Shopping"}
HelpRequest.create!(title: "Please help me to collect my shopping", help_category_id: 1)
# {id: 4, title: "Please help me to collect my shopping", help_category_id: 1}
以便我可以做类似的事情
request = HelpRequest.find(4)
# {id: 4, title: "Please help me to collect my shopping", help_category_id: 1}
request.help_category.title
# "Help with Shopping"
有人可以帮助我了解如何进行设置吗?
class AddHelpCategoryIdToHelpRequest < ActiveRecord::Migration[5.2]
def change
add_reference :help_requests, :help_categories, index: true
end
end
这会在help_category_id
表中添加help_requests
列和外键。然后添加关联:
class HelpRequest < ApplicationRecord
belongs_to :help_category
end
class HelpCategory < ApplicationRecord
has_many :help_requests
end
belongs_to
告诉ActiveRecord外键在
this表上。belongs_to
告诉Rails该模型是从另一个表引用的。然后您可以通过传递ID或记录来分配类别:
has_many
您也可以只创建/初始化关联记录:
help_category= HelpCategory.create!(title: "Help with Shopping")
hr = HelpRequest.create!(
title: "Please help me to collect my shopping",
help_category: help_category
)
# This is primarily done indirectly through the params
hr = HelpRequest.create!(
title: "Please help me to collect my shopping",
help_category_id: help_category.id
)