Cannot get Rails: autosave option for working with models

It may be something completely simple, but I cannot let my life work. For some reason: autosave does not actually autosave the base models.

Here is my diagram:

create_table :albums do |t| t.string :title t.text :review t.timestamps end create_table :songs do |t| t.integer :album_id t.string :name t.integer :length end create_table :cover_arts do |t| t.integer :album_id t.integer :artist end 

Here are my models:

 class Album < ActiveRecord::Base has_many :songs, :autosave => true has_one :cover_art, :autosave => true end class CoverArt < ActiveRecord::Base belongs_to :album end class Song < ActiveRecord::Base belongs_to :album end 

When I do the following in IRB for a cover album that is already in the database:

 a = Album.find(1) a.title = "New title" a.cover_art.artist = "New Artist" a.save 

It updates the album record, but not the CoverArt record. What am I doing wrong?

+4
source share
2 answers

When this happened to me, I found that the betternestedset plugin overwrites the update method without using alias_method_chain or anything else to support the existing call chain. I replaced the reternite update betternestedset and set a simple call to attr_readonly instead (similar to the existing attr_protected call in this plugin). Perhaps this will help someone.

+1
source

According to the docs, you should save the parent record, not just set a new value so that the child records also save.

 post = Post.find(1) post.title # => "The current global position of migrating ducks" post.author.name # => "alloy" post.title = "On the migration of ducks" post.author.name = "Eloy Duran" post.save post.reload post.title # => "On the migration of ducks" post.author.name # => "Eloy Duran" 
-one
source

All Articles