开发者

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

开发者 https://www.devze.com 2023-01-04 21:44 出处:网络
I recently run into a problem where records were marked as readonly. Checking out the documentation I found this:

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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消