【问题标题】:has_many and belongs_to with join tablehas_many 和 belongs_to 与连接表
【发布时间】:2017-03-30 18:06:17
【问题描述】:

我有Users 和Trucks。我希望能够说@truck.drivers << @users@user.truck = @truck

解决方案很简单,直到我希望将关系存储在连接表中。

# tables
:users
  :id

:truck_drivers
  :user_id
  :truck_id

:truck
  :id

我已经达到了可以说 @truck.drivers << @user@user.trucks << @truck 的位置,但为了我的理智,我想限制用户一次只占用一辆卡车。

有可能吗?带有连接表的 has_many/belongs_to?还是我应该尝试不同的方法?我没有为连接表使用第三种模型。这只是一张桌子。这是我目前所拥有的。

class User < ApplicationRecord
  has_and_belongs_to_many :trucks,
    join_table: :truck_drivers, # points to the table
    class_name: :Truck # looks for the truck model in the table
end

class Truck < ApplicationRecord
  belongs_to :company
  has_and_belongs_to_many :drivers,
    join_table: :truck_drivers,
    class_name: :User
end

我首先需要一个连接表的原因是因为每个User 可以有很多Roles:管理员、经理、司机、客户服务等。我认为添加一个没有意义truck_id 给所有用户,如果所有用户都不会使用卡车。

【问题讨论】:

    标签: ruby-on-rails ruby join


    【解决方案1】:

    看起来你应该能够做这样的事情:

    @user.trucks << @truck unless @user.trucks.any?
    

    【讨论】:

      【解决方案2】:

      是的,这是使用:through 关键字的rails 标准策略。

      rails 文档:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

      使用truck_iduser_id 制作一个名为 TruckUser 的模型

      然后编辑你的类:

      class User < ApplicationRecord
        has_many :truck_users
        has_many :trucks, through: :truck_users
      end
      
      class Truck < ApplicationRecord
        belongs_to :company
        has_many :truck_users
        has_many :drivers, through: :truck_users
      end
      
      class TruckUser < ApplicationRecord
        belongs_to :truck
        belongs_to :user
      end
      

      【讨论】:

      • 有没有办法限制每个用户一辆卡车?
      • @CruzNunez 你用两种方式写了has_any_belongs_to_many
      • 你是说你想让一辆卡车有很多用户,但一个用户应该只有一辆卡车?
      • 或者说保持数据库结构不变但应用限制?
      • 我知道我有两种方式。但我问我是否可以让它像belongs_to 一样运作。您如何应用限制?
      猜你喜欢
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 2022-07-08
      相关资源
      最近更新 更多