Eager load polymorphic association in Rails (clear code example included)Rails :include vs. :joinsEager loading of polymorphic associations in ActiveRecordrails 3, joining on more three tablesRails: Structuring a query involving a polymorphic association and STIIn Rails, how can I make ActiveRecord associations for two models that reference each other in different ways?Eager load polymorphicrails 4 scope through multiple has_one associationsEager load (includes) polymorphic associationRails Multiple checkboxes with associated Text fieldsRails - get polymorphic children from collection as ActiveRecord::Relation

How to detach yourself from a character you're going to kill?

Uncommanded roll at high speed

Thousands and thousands of words

What is game ban VS VAC ban in steam?

How can I offer a test ride while selling a bike?

What was this black-and-white film set in the Arctic or Antarctic where the monster/alien gets fried in the end?

Team member doesn't give me the minimum time to complete a talk

Are UK pensions taxed twice?

Select row of data if next row contains zero

Differences between “pas vrai ?”, “c’est ça ?”, “hein ?”, and “n’est-ce pas ?”

Smart people send dumb people to a new planet on a space craft that crashes into a body of water

If Sweden was to magically float away, at what altitude would it be visible from the southern hemisphere?

How should I push back against my job assigning "homework"?

Windows 10 Programs start without visual Interface

Why were the Night's Watch required to be celibate?

Infinitely many hats

Intuition behind eigenvalues of an adjacency matrix

How did early x86 BIOS programmers manage to program full blown TUIs given very few bytes of ROM/EPROM?

Where can I find the list of all tendons in the human body?

Biblical Basis for 400 years of silence between old and new testament

What does the behaviour of water on the skin of an aircraft in flight tell us?

The qvolume of an integer

Points within polygons in different projections

Is a hash a zero-knowledge proof?



Eager load polymorphic association in Rails (clear code example included)


Rails :include vs. :joinsEager loading of polymorphic associations in ActiveRecordrails 3, joining on more three tablesRails: Structuring a query involving a polymorphic association and STIIn Rails, how can I make ActiveRecord associations for two models that reference each other in different ways?Eager load polymorphicrails 4 scope through multiple has_one associationsEager load (includes) polymorphic associationRails Multiple checkboxes with associated Text fieldsRails - get polymorphic children from collection as ActiveRecord::Relation






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have following db (Postgresql) structure in Rails 5:



class Book < ApplicationRecord
belongs_to :location
end

class Song < ApplicationRecord
belongs_to :location
end

class Location < ApplicationRecord
# position INT
end

class Item < ApplicationRecord
belongs_to :product, polymorphic: true # Book or Song
has_one :location, through: :product
end

# Expected result
Item.includes(product: :location).order('locations.position ASC')
Item.first.location

# Actual result
# ActiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the polymorphic association :product)


But I have trouble for referencing Location through polymorphic Product. May be I missed some options here and selected wrong DB structure? Could you advise some "Rails way" workarounds here, rather then raw sql?










share|improve this question




























    0















    I have following db (Postgresql) structure in Rails 5:



    class Book < ApplicationRecord
    belongs_to :location
    end

    class Song < ApplicationRecord
    belongs_to :location
    end

    class Location < ApplicationRecord
    # position INT
    end

    class Item < ApplicationRecord
    belongs_to :product, polymorphic: true # Book or Song
    has_one :location, through: :product
    end

    # Expected result
    Item.includes(product: :location).order('locations.position ASC')
    Item.first.location

    # Actual result
    # ActiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the polymorphic association :product)


    But I have trouble for referencing Location through polymorphic Product. May be I missed some options here and selected wrong DB structure? Could you advise some "Rails way" workarounds here, rather then raw sql?










    share|improve this question
























      0












      0








      0








      I have following db (Postgresql) structure in Rails 5:



      class Book < ApplicationRecord
      belongs_to :location
      end

      class Song < ApplicationRecord
      belongs_to :location
      end

      class Location < ApplicationRecord
      # position INT
      end

      class Item < ApplicationRecord
      belongs_to :product, polymorphic: true # Book or Song
      has_one :location, through: :product
      end

      # Expected result
      Item.includes(product: :location).order('locations.position ASC')
      Item.first.location

      # Actual result
      # ActiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the polymorphic association :product)


      But I have trouble for referencing Location through polymorphic Product. May be I missed some options here and selected wrong DB structure? Could you advise some "Rails way" workarounds here, rather then raw sql?










      share|improve this question














      I have following db (Postgresql) structure in Rails 5:



      class Book < ApplicationRecord
      belongs_to :location
      end

      class Song < ApplicationRecord
      belongs_to :location
      end

      class Location < ApplicationRecord
      # position INT
      end

      class Item < ApplicationRecord
      belongs_to :product, polymorphic: true # Book or Song
      has_one :location, through: :product
      end

      # Expected result
      Item.includes(product: :location).order('locations.position ASC')
      Item.first.location

      # Actual result
      # ActiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the polymorphic association :product)


      But I have trouble for referencing Location through polymorphic Product. May be I missed some options here and selected wrong DB structure? Could you advise some "Rails way" workarounds here, rather then raw sql?







      ruby-on-rails ruby postgresql activerecord






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 9:52









      MolfarMolfar

      5291033




      5291033






















          2 Answers
          2






          active

          oldest

          votes


















          1














          I don't understand your items model but polymorphic is normally set up like this:



          class Book < ApplicationRecord
          has_one :location, as: :locateable, class_name: Location
          end

          class Song < ApplicationRecord
          has_one :location, as: :locateable, class_name: Location
          end

          class Location < ApplicationRecord
          belongs_to :locateable, polymorphic: true
          end


          But please refer to documentation on polymorphic relation






          share|improve this answer






























            1














            The reason is you doing it wrong.in your code you are saying that product is going to be polymorphic but still with wrong syntax and not including that polymorphic association in other models ..check out the above answer and do check the rails official guide for further clarification.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55322533%2feager-load-polymorphic-association-in-rails-clear-code-example-included%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              I don't understand your items model but polymorphic is normally set up like this:



              class Book < ApplicationRecord
              has_one :location, as: :locateable, class_name: Location
              end

              class Song < ApplicationRecord
              has_one :location, as: :locateable, class_name: Location
              end

              class Location < ApplicationRecord
              belongs_to :locateable, polymorphic: true
              end


              But please refer to documentation on polymorphic relation






              share|improve this answer



























                1














                I don't understand your items model but polymorphic is normally set up like this:



                class Book < ApplicationRecord
                has_one :location, as: :locateable, class_name: Location
                end

                class Song < ApplicationRecord
                has_one :location, as: :locateable, class_name: Location
                end

                class Location < ApplicationRecord
                belongs_to :locateable, polymorphic: true
                end


                But please refer to documentation on polymorphic relation






                share|improve this answer

























                  1












                  1








                  1







                  I don't understand your items model but polymorphic is normally set up like this:



                  class Book < ApplicationRecord
                  has_one :location, as: :locateable, class_name: Location
                  end

                  class Song < ApplicationRecord
                  has_one :location, as: :locateable, class_name: Location
                  end

                  class Location < ApplicationRecord
                  belongs_to :locateable, polymorphic: true
                  end


                  But please refer to documentation on polymorphic relation






                  share|improve this answer













                  I don't understand your items model but polymorphic is normally set up like this:



                  class Book < ApplicationRecord
                  has_one :location, as: :locateable, class_name: Location
                  end

                  class Song < ApplicationRecord
                  has_one :location, as: :locateable, class_name: Location
                  end

                  class Location < ApplicationRecord
                  belongs_to :locateable, polymorphic: true
                  end


                  But please refer to documentation on polymorphic relation







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 at 12:06









                  lacostenycoderlacostenycoder

                  5,07621431




                  5,07621431























                      1














                      The reason is you doing it wrong.in your code you are saying that product is going to be polymorphic but still with wrong syntax and not including that polymorphic association in other models ..check out the above answer and do check the rails official guide for further clarification.






                      share|improve this answer



























                        1














                        The reason is you doing it wrong.in your code you are saying that product is going to be polymorphic but still with wrong syntax and not including that polymorphic association in other models ..check out the above answer and do check the rails official guide for further clarification.






                        share|improve this answer

























                          1












                          1








                          1







                          The reason is you doing it wrong.in your code you are saying that product is going to be polymorphic but still with wrong syntax and not including that polymorphic association in other models ..check out the above answer and do check the rails official guide for further clarification.






                          share|improve this answer













                          The reason is you doing it wrong.in your code you are saying that product is going to be polymorphic but still with wrong syntax and not including that polymorphic association in other models ..check out the above answer and do check the rails official guide for further clarification.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 25 at 1:19









                          The Digital AcademyThe Digital Academy

                          124




                          124



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55322533%2feager-load-polymorphic-association-in-rails-clear-code-example-included%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript