我已经建立了一个用户和 friend 关系模型,但问题是通过这些关联我可以给自己加好友。我已经成功地在我的 View 和 Controller 中抑制了它,但从逻辑上讲,它应该在模型中被抑制,因为我仍然可以从控制台创建我想避免的友谊。
用户模型
has_many :user_friendships
has_many :friends, through: :user_friendships,
conditions: { user_friendships: { state: 'accepted' } }
用户友谊模型
belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
其他一切都运行良好,例如添加、阻止、删除、请求好友,我的模型的唯一问题是我也可以为自己加好友,这是我想避免的。
最佳答案
向UserFriendship
添加验证:
validate :cannot_friend_self
def cannot_friend_self
errors.add(:friend_id, "cannot friend self") unless user_id != friend_id
end
关于mysql - 能够在 Rails 控制台中将自己添加为好友,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16849232/