使用哪种Rails关联以及如何使用它们

问题描述 投票:1回答:1

我有一个Rails API,目前有两个模型,HelpCategoryHelpRequest

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"

有人可以帮助我了解如何进行设置吗?

ruby-on-rails ruby-on-rails-5 rails-activerecord rails-api
1个回答
0
投票
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
)
© www.soinside.com 2019 - 2024. All rights reserved.