【问题标题】:How can an User model both belong_to and Has_many of another model depending if the user is an Admin or not?根据用户是否是管理员,用户如何对另一个模型的 belongs_to 和 Has_many 建模?
【发布时间】:2015-03-07 23:18:52
【问题描述】:
我正在尝试创建一些 Active Record 关联来为农业农场建模,到目前为止,我已经有了用户模型和管理员布尔字段,这意味着一些用户是管理员,而其他用户不是。我也有一个农场模型。
现在,如果用户 if 和 admin User 它拥有_many 个农场,但如果用户不是 admin 用户,则它属于_一个农场(员工)。所以基本上我的问题是用户如何根据其管理员状态来归属或拥有?或者哪种是建模这种关系的正确方法,我是否必须为管理员创建不同的模型?
谢谢
【问题讨论】:
标签:
ruby-on-rails
ruby
activerecord
associations
【解决方案1】:
在我看来,您的模型实际上有两种不同的关联。一种定义所有权,另一种定义用户的工作地点:
belongs_to :farm_employed_at, class_name: "Farm"
has_many :owned_farms, class_name: "Farm"
然后您可以添加验证以确保只设置正确的关联类型:
validates :farm_association
private
def farm_assosiation
if admin?
errors.add(:base, "Admins should not work") if farm_employed_at
else
errors.add(:base, "Users aren't allowed to own farms") if owned_farms.any?
end
end