Mark
Mark

Reputation: 6455

Rails - shovelling into an array

I have a model, a DynamicPage, that can have a featured_child_dynamic_page as follows:

has_many :dynamic_page_featured_relations
has_many :child_featured_dynamic_pages, through: :dynamic_page_featured_relations, source: :dynamic_page

In my controller I'm trying to do the following, where both parent_page and featured_child_page are saved dynamic pages. :

parent_page.child_featured_dynamic_pages << child_featured_page

After I run this operation in console, it returns the child_featured_page. However when I run parent_page.child_featured_dynamic_pages it returns an empty association. I have also tried:

parent_page.child_featured_dynamic_page_ids << child_featured_page.id

Once more this returns the ID, however when I check the array of ID's it is empty. Any advice is appreciated

Upvotes: 0

Views: 77

Answers (1)

JayJay
JayJay

Reputation: 814

You need to save parent_page after the assignment:

parent_page.save

This persists the object with its new child objects to the database, creating the necessary association records.

Upvotes: 1

Related Questions