views:

29

answers:

2

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?

A: 

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
Daniel Abrahamsson
+1  A: 

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

fullware
Thank you for your answer, but I use it as a pure selection scope and don't normally need the association class otherwise. In those cases I do though, it might be better to use your solution because of efficiency reasons.
Daniel Abrahamsson