如何防止使用特定ID创建类的实例

时间:2015-12-26 08:32:34

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我有2个型号:帖子,用户。用户不能喜欢他的帖子,那么如何阻止创建模型的实例(user_id:creator,post_id:由“创建者”创建)?

2 个答案:

答案 0 :(得分:1)

您可以在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

答案 1 :(得分:0)

Another implementation I found ...

#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