【问题标题】:Rails has_one per scopeRails has_one 每个范围
【发布时间】:2013-05-15 00:59:10
【问题描述】:

我有如下三个模型:

    class User < ActiveRecord::Base
      ...
      has_many :feeds
      ...
    end

    class Project < ActiceRecord::Base
      ...
      has_many :feeds
      has_many :users, through: :feeds
      ...
    end

    class Feed < ActiveRecord::Base
      ...
      belongs_to :user
      belongs_to :project
      ...
    end

我想模拟用户每个项目最多可以拥有一个提要的情况。我知道我可以在 Feed 类中的自定义验证器中执行此检查,但是有没有办法仅使用 ActiveRecord 关联来对此进行建模?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations has-many


    【解决方案1】:

    您可以在 Feed.rb 上做到这一点:

    validates :user_id, :uniqueness => {:scope => :project_id}
    

    【讨论】:

    • 谢谢 Anezio,很抱歉我这么晚才接受你的回答。正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多