Can't get Rails :autosave option to work on models
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_ma开发者_StackOverflow社区ny :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?
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.
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"
精彩评论