简体   繁体   中英

How to prevent user to subscribe twice to the same App?

I have following models.

I dont want that User can subscribe many times to the same App

So this shouldn`t be possible:

User.last.apps
=> [#<App id: 78, name: "Name">, #<App id: 78, name: "Name">]


User.last.subscriptions
=> [#<Subscription id: 78, app_id: 78>, #<Subscription id: 79, app_id: 78>]

Models

User
  has_many :subscriptions, :dependent => :destroy
  has_many :apps, through: :subscriptions

Subscription
  validates :user_id, uniqueness: { scope: :app_id }
  belongs_to :user, touch: true
  belongs_to :app 

App  
  validates_uniqueness_of :name  
  belongs_to :user, touch: true
  belongs_to :app    

您可以向关联添加唯一约束:

has_many :apps, through: :subscriptions, uniq: true

我向订阅表中的数据库添加了唯一索引。

add_index :subscriptions, [:user_id, :app_id], unique: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM