【问题标题】:What Rails associations to use and how to use them使用什么 Rails 关联以及如何使用它们
【发布时间】:2020-03-19 00:07:43
【问题描述】:

我有一个 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】:

    这只是您的一对多关联。

    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 表上。 has_many 告诉 Rails 这个模型是从另一个表中引用的。

    然后您可以通过传递 id 或记录来分配类别:

    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
    )
    

    您也可以只创建/初始化关联记录:

    hr = help_category.help_requests.create!(
      title: "Please help me to collect my shopping", 
    )
    

    【讨论】:

      猜你喜欢
      • 2011-07-04
      • 2017-10-26
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      相关资源
      最近更新 更多