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

标签 ruby-on-rails ruby

我认为我的 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/

相关文章:

ruby-on-rails - Bundler:读取服务器证书 B:证书验证失败(OpenSSL::SSL::SSLError)

ruby - 为什么我们将 0 作为参数传递给 "exit"?

css - 为什么我的图像和样式表在 RoR 应用程序中不起作用?

ruby-on-rails - 从模型重新索引后 Searchkick 索引为空

javascript - jquery 和 ajax 工具提示不适用于实时加载的内容

ruby-on-rails - ruby on rails 中的外键如何命名?

ruby-on-rails - 删除模型和表,以便可以在 Rails 中重新开始

mysql - rake db :migrate - 问题

ruby - 我如何在 Clojure 中编写 Ruby 的 each_cons?

ruby-on-rails - 在内存 Ruby/Rails 中压缩和加密文件