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

scoped relations and find_or_create_by and find_or_initialize_by

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.1.0
    • Affects Version/s: None
    • Component/s: None

      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

      Unable to find source-code formatter for language: find_or_initialize_by. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      
      

      .

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

      Can anyone decide?

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

              Created:
              Updated:
              Resolved: