Daniel Abrahamsson
Daniel Abrahamsson

Reputation: 1965

Why can't records with piggy-back attributes be saved?

I recently run into a problem where records were marked as readonly. Checking out the documentation I found this:

"Records loaded through joins with piggy-back attributes will be marked as read only since they cannot be saved. "

Why not? My model looks like the following:

class MailAccount
    belongs_to :account, :class_name => "UserAccount"
    named_scope :active, :joins => :account, 
      :conditions => "user_accounts.archived_at IS NULL"
end

I find no reason why models loaded retrieved with this named scope can not be saved. Any ideas?

Upvotes: 2

Views: 576

Answers (2)

aceofspades
aceofspades

Reputation: 7586

When you use a :join, the ActiveRecord model for that associated object is not instantiated. You should use :include instead.

Upvotes: 1

Daniel Abrahamsson
Daniel Abrahamsson

Reputation: 1965

It turned out I had to add :select => "mail_accounts.*" to the scope, or otherwise the query would store attributes from user_accounts in the MailAccount object, which prevented it from being saved.

So the proper code to use is:

class MailAccount
    belongs_to :account, :class_name => "UserAccount"
    named_scope :active, :joins => :account, 
      :conditions => "user_accounts.archived_at IS NULL",
      :select => "mail_accounts.*"
end

Upvotes: 4

Related Questions