Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2707

scoped relations and find_or_create_by and find_or_initialize_by

    XMLWordPrintable

    Details

    • Type: Task
    • Status: Closed
    • Resolution: Done
    • Affects Version/s: None
    • Fix Version/s: 3.1.0
    • Component/s: None
    • Labels:

      Description

      Hello.

      I wanted to use this code

      @order = @eshop.orders.for_customer(current_customer).cart.find_or_create_by(session_id: session[:cart]
      

      But when document wasn't found, it was created without relations. for_customer and cart are scopes. orders is has_many relation to eshop. eshop_id was nil and customer_id was also nil. Cart is state for order. It was also in blank state.

      I'm using this syntax now to avoid this:

      begin
        @order = @eshop.orders.for_customer(current_customer).cart.find_by(session_id: session[:cart])
      rescue Mongoid::Errors::DocumentNotFound
        @order = @eshop.orders.for_customer(current_customer).cart.create(session_id: session[:cart])
      end
      

      And it works.

      Same behaviour is for

       

      .

      I'm not sure if this is bug or expected behaviour.

      Can anyone decide?

        Attachments

          Activity

            People

            Assignee:
            durran Durran Jordan
            Reporter:
            simi simi
            Participants:
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: