Jump to content

The ultimate community for Ruby on Rails developers.


How do I avoid concurrency belongs_to and has_many association?


  • Please log in to reply
1 reply to this topic

#1 ricardodovalle



  • Members
  • 1 posts

Posted 09 August 2014 - 08:10 AM

How do I avoid concurrency and keep the data integrity if one user submit a form before the other?
My issue is that the last user to submit the person/_form.rb will get all chosen cards, same the cards that first user chose and I want to prohibit that.
    # person.rb
    class Person < ActiveRecord::Base
      has_many :cards

    # card.rb
    class Card < ActiveRecord::Base
      belongs_to :person
      scope :not_assigned_to_a_person, -> { Card.where(person_id: nil) }
    # create_cards.rb
    create_table :cards do |column|
      column.references :person, index: true

    # person/_form.rb
    = f.input :card_ids,
        collection: Card.not_assigned_to_a_person,
        label_method: :name, value_method: :id,
        input_html: { multiple: true }


#2 Ohm



  • Moderators
  • 529 posts
  • LocationCopenhagen

Posted 11 August 2014 - 05:30 AM

Do a check in the controller before blindly adding the cards to the person.

cards_to_be_assigned = Card.not_assigned_to_a_person.where(id: params[:card_ids])

cards_to_be_assigned will be the cards in the form that are still assignable. 

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk

Also tagged with one or more of these keywords: association

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users