gpt4 book ai didi

ruby-on-rails - 我应该在 Rails 中使用多重传递关联吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:58 24 4
gpt4 key购买 nike

我认为我的 Rails 应用程序中可能需要多传递关联。我需要一些帮助来做出这个决定和实现逻辑。

我有 4 个模型。

1. User - has_and_belongs_to_many :locations
2. Locations - has_and_belongs_to_many :users
3. Customer - model in question
4. Job - model in question

每个用户都被分配到特定位置,以便用户可以查看客户并编辑与其关联的位置的工作。

我认为我需要多传递关联的部分是我的 CustomerJob 模型。

本质上,应该有一个客户记录。客户应该在许多地方有许多工作。但是,用户应该只看到与他们相关联的位置的客户。这是让我卡住的部分。

更新

只是想出一个主意,也许这个协会会奏效:

User has_and_belongs_to_many :locations
Location has_and_belongs_to_many :users
Customer has_and_belongs_to_many :locations, has_many :jobs
Job belongs_to :customers, belongs_to :locations

然后我可以通过以下方式访问给定位置的所有客户

User has_many :customers, through: :locations
User has_many :jobs, through: :locations

最佳答案

Trying my best to explain. A user should be able to login and see all of their locations that they do work. They should be able to select a location and see all of the customers for that location and also see all of the jobs for that location (a location could be like a region or city). Its possible that a user may work under the US location and also the Canada location so if that user selects Canada, then the user should only be able to view (via association) the Canada customers and the Canada jobs

下面的代码可能会解决您的问题。

    class User < ActiveRecord::Base
has_many_and_belongs_to :locations
has_many :customers, through: :locations
has_many :jobs, through: :locations
end

class Location < ActiveRecord::Base
has_many_and_belongs_to :users
has_many_and_belongs_to :customers
has_many_and_belongs_to :jobs
end

class Customer < ActiveRecord::Base
has_and_belongs_to_many :locations,
end

class Job < ActiveRecord::Base
has_many_and_belongs_to :locations
end

现在在 Controller 中你可以使用:

say params = {region: 'canada'}

@canada_jobs = current_user.jobs.where(locations: {region: params[:region]})
@canada_customers = current_user.customers.where(locations: {region: params[:region]})

关于ruby-on-rails - 我应该在 Rails 中使用多重传递关联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48812259/

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