views:

331

answers:

2

This may be something totally simple, but I can't for the life of me get this working. For some reason, :autosave isn't actually autosaving underlying models.

Here is my schema:

    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 an album with cover art 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?

A: 

According to the docs, you have to save the parent record, not just set a new value, for the child records to 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"
floyd
sorry, I left that out of the message above - I'm actually doing that as well. So that isn't the problem, either - I've edited my post above to clarify.
mrjake2
perhaps you can include the output you're getting in console?
floyd
Hi Floyd, the only output I'm getting in the console is a return value of "true" for the save. Looking at the development.log file, this is because the album object was successfully saved. However, the cover_art object is not. It doesn't show up in the log files at all. So unfortunately there are no error messages either in the console or the log files to indicate what the problem might be.
mrjake2
I meant the whole process you're going through to confirm the value hasn't been set correctly, using the reload etc. Unfortunately, there's not a lot obvious that could be going wrong here, so it's difficult to answer your question...
floyd
A: 

When this happened to me, I found the betternestedset plugin was overwriting the update method without using alias_method_chain or anything else to maintain the existing call chain. I replaced betternestedset's update rewrite and put a simple attr_readonly call in its place (similar to the existing attr_protected call in that plugin). Perhaps this will help someone somewhere.

Stephen Friedman