【问题标题】:Rails Join Table UniquenessRails 连接表的唯一性
【发布时间】:2015-07-15 21:18:12
【问题描述】:

我正在尝试通过 user_id 和 restaurant_id 验证连接表 Employee 中行的唯一性。

其他帖子提出了类似的建议,但它不适用于 ":id" 作为属性,因为当我测试它时它仍然会应用重复项。

validates_uniqueness_of :id, :scope => [:user_id, :restaurant_id]

也许铲子分配@restaurant.users << @user 没有验证唯一性?

型号:

class Restaurant < ActiveRecord::Base
    has_many :employees
    has_many :users, through: :employees
end

class User < ActiveRecord::Base
  has_many :employees
  has_many :restaurants, through: :employees
end

class Employee < ActiveRecord::Base
    belongs_to :restaurant
    belongs_to :user
end

【问题讨论】:

    标签: ruby-on-rails join activerecord


    【解决方案1】:

    我能找到的最佳解决方法是像这样在控制器中进行验证:

    if @restaurant.users.include?(@user)

    在我的情况下这很好,因为我只在我的应用程序的一个地方执行该操作,但我想知道在其他情况下是否有更好的方法让它更干燥。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多