Rails: Creating/updating has_many relationships for existing has_many recordsRails has_many with alias nameBug? I've to mass-assign params two times to update has_many associationMongoid - Updating Nested AttributesRails find record with zero has_many records associatedCreating / updating locations while creating a checkin in RailsCan't Mass assign attributes with nested formRails has_many :through with :primary_keyAdding Role dynamically through Form USing Rolify along with Devise and CancanRails 4 accepts_nested_attributes_for for has_many through relationship: :_destroy is not workingRails 4 relationships and Postgres foreign key constraints

How did Doctor Strange see the winning outcome in Avengers: Infinity War?

Is there a problem with hiding "forgot password" until it's needed?

Is this apparent Class Action settlement a spam message?

Opposite of a diet

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

What Brexit proposals are on the table in the indicative votes on the 27th of March 2019?

How does Loki do this?

You cannot touch me, but I can touch you, who am I?

Trouble understanding the speech of overseas colleagues

How does it work when somebody invests in my business?

Sequence of Tenses: Translating the subjunctive

Method to test if a number is a perfect power?

Escape a backup date in a file name

Why, precisely, is argon used in neutrino experiments?

Increase performance creating Mandelbrot set in python

Why Were Madagascar and New Zealand Discovered So Late?

How to be diplomatic in refusing to write code that breaches the privacy of our users

Was Spock the First Vulcan in Starfleet?

For a non-Jew, is there a punishment for not observing the 7 Noahide Laws?

What is the difference between "behavior" and "behaviour"?

How to Reset Passwords on Multiple Websites Easily?

India just shot down a satellite from the ground. At what altitude range is the resulting debris field?

Why not increase contact surface when reentering the atmosphere?

How do I extract a value from a time formatted value in excel?



Rails: Creating/updating has_many relationships for existing has_many records


Rails has_many with alias nameBug? I've to mass-assign params two times to update has_many associationMongoid - Updating Nested AttributesRails find record with zero has_many records associatedCreating / updating locations while creating a checkin in RailsCan't Mass assign attributes with nested formRails has_many :through with :primary_keyAdding Role dynamically through Form USing Rolify along with Devise and CancanRails 4 accepts_nested_attributes_for for has_many through relationship: :_destroy is not workingRails 4 relationships and Postgres foreign key constraints













0















Given:



class Group < ApplicationRecord
has_many :customers, inverse_of: :group
accepts_nested_attributes_for :customers, allow_destroy: true
end

class Customer < ApplicationRecord
belongs_to :group, inverse_of: :customers
end


I want to create/update a group and assign existing customers to the group e.g.:



Group.new(customers_attributes: [ id: 1 , id: 2 ])


This does not work though because Rails will just throw ActiveRecord::RecordNotFound: Couldn't find Customer with ID=1 for Group with ID= (or ID=the_group_id if I'm updating a Group). Only way I've found to fix it is just extract customers_attributes and then do a separate Customer.where(id: [1,2]).update_all(group_id: 'groups_id') after the Group save! call.



Anyone else come across this? I feel like a way to fix it would be to have a key like _existing: true inside customers_attributes (much like _destroy: true is used to nullify the foreign key) could work. Or does something like this violate a Rails principle that I'm not seeing?










share|improve this question


























    0















    Given:



    class Group < ApplicationRecord
    has_many :customers, inverse_of: :group
    accepts_nested_attributes_for :customers, allow_destroy: true
    end

    class Customer < ApplicationRecord
    belongs_to :group, inverse_of: :customers
    end


    I want to create/update a group and assign existing customers to the group e.g.:



    Group.new(customers_attributes: [ id: 1 , id: 2 ])


    This does not work though because Rails will just throw ActiveRecord::RecordNotFound: Couldn't find Customer with ID=1 for Group with ID= (or ID=the_group_id if I'm updating a Group). Only way I've found to fix it is just extract customers_attributes and then do a separate Customer.where(id: [1,2]).update_all(group_id: 'groups_id') after the Group save! call.



    Anyone else come across this? I feel like a way to fix it would be to have a key like _existing: true inside customers_attributes (much like _destroy: true is used to nullify the foreign key) could work. Or does something like this violate a Rails principle that I'm not seeing?










    share|improve this question
























      0












      0








      0








      Given:



      class Group < ApplicationRecord
      has_many :customers, inverse_of: :group
      accepts_nested_attributes_for :customers, allow_destroy: true
      end

      class Customer < ApplicationRecord
      belongs_to :group, inverse_of: :customers
      end


      I want to create/update a group and assign existing customers to the group e.g.:



      Group.new(customers_attributes: [ id: 1 , id: 2 ])


      This does not work though because Rails will just throw ActiveRecord::RecordNotFound: Couldn't find Customer with ID=1 for Group with ID= (or ID=the_group_id if I'm updating a Group). Only way I've found to fix it is just extract customers_attributes and then do a separate Customer.where(id: [1,2]).update_all(group_id: 'groups_id') after the Group save! call.



      Anyone else come across this? I feel like a way to fix it would be to have a key like _existing: true inside customers_attributes (much like _destroy: true is used to nullify the foreign key) could work. Or does something like this violate a Rails principle that I'm not seeing?










      share|improve this question














      Given:



      class Group < ApplicationRecord
      has_many :customers, inverse_of: :group
      accepts_nested_attributes_for :customers, allow_destroy: true
      end

      class Customer < ApplicationRecord
      belongs_to :group, inverse_of: :customers
      end


      I want to create/update a group and assign existing customers to the group e.g.:



      Group.new(customers_attributes: [ id: 1 , id: 2 ])


      This does not work though because Rails will just throw ActiveRecord::RecordNotFound: Couldn't find Customer with ID=1 for Group with ID= (or ID=the_group_id if I'm updating a Group). Only way I've found to fix it is just extract customers_attributes and then do a separate Customer.where(id: [1,2]).update_all(group_id: 'groups_id') after the Group save! call.



      Anyone else come across this? I feel like a way to fix it would be to have a key like _existing: true inside customers_attributes (much like _destroy: true is used to nullify the foreign key) could work. Or does something like this violate a Rails principle that I'm not seeing?







      ruby-on-rails ruby has-many






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 7 at 12:52









      user701847user701847

      166113




      166113






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Actually, you don't need to use nested attributes for this, you can instead set the association_ids attribute directly:



          Group.new(customer_ids: [1, 2])


          This will automatically update the group_id on each referenced Customer when the record is saved.






          share|improve this answer


















          • 1





            Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

            – user701847
            Mar 7 at 13:20











          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%2f55044270%2frails-creating-updating-has-many-relationships-for-existing-has-many-records%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Actually, you don't need to use nested attributes for this, you can instead set the association_ids attribute directly:



          Group.new(customer_ids: [1, 2])


          This will automatically update the group_id on each referenced Customer when the record is saved.






          share|improve this answer


















          • 1





            Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

            – user701847
            Mar 7 at 13:20
















          1














          Actually, you don't need to use nested attributes for this, you can instead set the association_ids attribute directly:



          Group.new(customer_ids: [1, 2])


          This will automatically update the group_id on each referenced Customer when the record is saved.






          share|improve this answer


















          • 1





            Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

            – user701847
            Mar 7 at 13:20














          1












          1








          1







          Actually, you don't need to use nested attributes for this, you can instead set the association_ids attribute directly:



          Group.new(customer_ids: [1, 2])


          This will automatically update the group_id on each referenced Customer when the record is saved.






          share|improve this answer













          Actually, you don't need to use nested attributes for this, you can instead set the association_ids attribute directly:



          Group.new(customer_ids: [1, 2])


          This will automatically update the group_id on each referenced Customer when the record is saved.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 13:17









          James PageJames Page

          111




          111







          • 1





            Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

            – user701847
            Mar 7 at 13:20













          • 1





            Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

            – user701847
            Mar 7 at 13:20








          1




          1





          Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

          – user701847
          Mar 7 at 13:20






          Ah, I forgot to mention that. So while that's fine for creating a new group, if you do that when updating a group, it erases any previous customers that may have been attached to that Group. I'm kind of looking for an all-in-one solution.

          – user701847
          Mar 7 at 13:20




















          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%2f55044270%2frails-creating-updating-has-many-relationships-for-existing-has-many-records%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

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved