gpt4 book ai didi

ruby-on-rails - rails : How to create has_many through relationships via the ids in the model?

转载 作者:行者123 更新时间:2023-12-02 20:00:03 26 4
gpt4 key购买 nike

我有三个模型:CustomerBranchCustomerBranch

在客户模型中:

has_many :customer_branches, inverse_of: :customer
has_many :branches, through: :customer_branches

在分支模型中:

has_many :customer_branches, inverse_of: :branch, dependent: :restrict_with_exception
has_many :customers, through: :customer_branches

在 CustomerBranch 模型中:

belongs_to :customer, inverse_of: :customer_branches
belongs_to :branch, inverse_of: :customer_branches

这是一个仅 API 的应用程序,我将获得一组分支 id。现在我想根据收到的 ID 为客户分配/删除分支。

我有一个解决方案来处理这个问题,但我认为这不是最好的方法。这是我当前的解决方案:

attr_accessor :branches_ids
after_save :assign_branches

def assign_branches
return if self.branches_ids.nil?
old_branch_ids = self.branch_ids

remove_branch_ids = old_branch_ids - self.branches_ids

self.customer_branches.where(id: remove_branch_ids).delete_all if remove_branch_ids.present?

self.branches << Branch.where(id: self.branches_ids)
end

有没有更好的方法来处理这个问题?预先感谢!

最佳答案

好啦,回答一下问题。您可以直接在客户上设置 ID:

customer = Customer.find(1)
customer.branches_ids = [1,2,3]

Rails 将处理所有添加和删除。

还与新客户合作:

customer = Customer.new
customer.name = "blabla"
customer.branches_ids = [1,2,3]
customer.save

关于ruby-on-rails - rails : How to create has_many through relationships via the ids in the model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com