【问题标题】:Rails HABTM: Post.title uniqueness per User onlyRails HABTM:每个用户的 Post.title 唯一性
【发布时间】:2013-12-04 15:37:25
【问题描述】:

在 Rails 4 中,我有一个典型的 HABTM 设置;

class Author < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :authors
end

我想验证 Post.title 的唯一性,但仅限于每个 Author 的基础上。所以;

  • 作者 #1 可以拥有 Post.title 'My Post'
  • 作者 #2 可以拥有 Post.title 'My Post'
  • 但是,作者 #1 无法创建标题为“我的帖子”的第二个帖子

Post 允许拥有多个 Author,因此我不能只拥有 belongs_to 并使用 validates_uniqueness_of :title, scope: :author_id,而且我不确定如何最好地使用 HABTM。

这可以通过validates 实现吗?还是我需要callback 在保存之前先检查关联的Author 是否有匹配的Post.title


编辑

我使用以下迁移来设置连接表;

class CreateAuthorsPosts < ActiveRecord::Migration
  def change
    create_table :authors_posts, id: false, force: true do |t|
      t.belongs_to :author, index: true
      t.belongs_to :post, index: true
    end
    add_index :authors_posts, [:author_id, :post_id], unique: true
  end
end

【问题讨论】:

    标签: ruby-on-rails associations unique has-and-belongs-to-many


    【解决方案1】:

    我不相信你可以用预定义的验证器做你想做的事。

    您可以定义使用自定义方法的验证(请参阅Active Record Validations documentation

    类似

    class Post < ActiveRecord::Base
      has_and_belongs_to_many :authors
      validate :uniqueness_of_title_and_author
    
      def uniqueness_of_title_and_author
        if author.posts.where(title: self.title).exists?
          errors.add(:title, "must be unique")
        end
      end
    
    end
    

    每次调用#valid? 时都会检查Post

    【讨论】:

    • 我无法确定 if 条件。您能否更新您的答案以显示如何仅由创建它的作者检查帖子的 :title ?另外,我正在生成这样的新帖子; author.posts.create(...)。对吗?
    • 完成;我相信查询应该足以满足您的要求。是的,author.posts.create 是我添加作者新帖子的方式,除非你想修改它之前保存在这种情况下你应该做author.posts.build
    • 唉,我还是有问题,收到这个错误; NameError: undefined local variable or method `author' for #&lt;Post:0x007fa0b37cd8e0&gt;
    • 对,因为一篇文章有​​很多作者。唔。你有一个连接authorsposts 表的authors_posts 表吗?
    • 是的,连接表存在。我已经用迁移代码更新了我的问题以供参考。
    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 2017-10-01
    • 1970-01-01
    • 2014-02-06
    • 2021-03-08
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多