has_one通过关联或替代方式?

时间:2016-08-22 11:55:04

标签: ruby-on-rails activerecord

不确定如何设置表格和我正在尝试实现的关系。我以为我需要一个通过关系但是我看到一些帖子反对这一点。

我想要实现的是商店创建他们的服务列表,他们的员工从这个列表中选择他们所做的服务。

这是我到目前为止所拥有的:

class User
 has_many :staff
  # user and shop have relationship via roles (not shown for simplicity)
end

class Shop
  has_many :staff
  has_many :services
  # user and shop have relationship via roles (not shown for simplicity)
end

class Service
  belongs_to :shop
  has_many :staff through: :staff_services
end

class Staff
  belongs_to :shop
  belongs_to :user
  has_many :services through: :staff_services
end

class StaffService
  belongs_to :staff
  # ? has_one :service through: :shop
  # ? belongs_to :service
end

我不确定如何设置StaffServices的关系,以便员工只能从他们是员工的商店中选择服务。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要员工和服务之间的多对多关联。我相信你希望belongs_to :service表中有StaffService。这可以简化为隔离您正在使用的关联:

class Service
  has_many :staff, through: :staff_services
end

class Staff
  has_many :services, through: :staff_services
end

class StaffService
  belongs_to :staff
  belongs_to :service
end

我并不是说你在你的例子中得到的其他联想在任何方面都是无效或错误的 - 我只是想展示多对多的部分。你已经在Shop& amp;员工,商店&服务将允许您轻松构建范围,这将限制所涉及的员工和服务集。

如果您还没有,我建议您仔细阅读Rails Guide to Associations

相关问题