如何防止创建具有特定 ID 的 class 的实例

How to prevent creating the instance of the class with specific IDs

我有 2 个模型:Post,用户。用户不能喜欢他的 post,那么我如何才能阻止创建模型实例(user_id:创建者,"creator" 的 post_id:created)?

您可以在您的 Like 模型中验证:

class Like < ActiveRecord::Base
  validates_presence_of :user_id, :post_id
  validate :voter_not_author

  private

  def voter_not_author
    if self.user_id == self.post.try(:user_id)
      self.errors[:base] << "Author can't be the voter"
    end
  end
end

...

#app/models/like.rb
class Like < ActiveRecord::Base
   validates :user_id, exclusion: {in: ->(u) { [Post.find(u.post_id).user_id] }} #-> user_id cannot equal post.user_id
end

如果你想摆脱数据库查询,你必须关联模型并使用 inverse_of:

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :likes
end

#app/models/like.rb
class Like < ActiveRecord::Base
   belongs_to :user
   belongs_to :post, inverse_of: :likes

   validates :user_id, exclusion: {in: ->(u) { u.post.user_id }}
end

#app/models/post.rb
class Post < ActiveRecord::Base
   has_many :likes, inverse_of: :post
end