Limit number of objects in has_many association

后端 未结 4 400
情书的邮戳
情书的邮戳 2020-12-02 09:38

I have an album which has_many photos. A counter_cache setup updates the photos_count column in the album table. How do I limit the number of photos for an album?

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 10:01

    ActiveRecord::Base.transaction do
      ActiveRecord::Base.connection.execute('LOCK TABLE pictures IN EXCLUSIVE MODE')
      if (@album.pictures.count < 10) 
        @album.pictures.create()
      end
    end
    

    I believe this is the most correct solution. It guards against concurrency issues/race conditions.

提交回复
热议问题