has_many和belongs_to与联接表

时间:2017-03-30 18:06:18

标签: ruby-on-rails ruby join

我有UserTruck s。我希望能够说出@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可以有很多Role:管理员,经理,司机,客户服务等等。我认为它没有&#39;如果所有用户都不打算使用卡车,那么向所有用户添加truck_id是有意义的。

2 个答案:

答案 0 :(得分:1)

看起来你应该能够做类似的事情:

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

答案 1 :(得分:0)

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

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

使用TruckUsertruck_id制作一个名为 user_id的模型

然后编辑你的课程:

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
相关问题