mercredi 31 mai 2017

Ruby on Rails: Anything selected with 'joins' is readonly

So we're having some difficulty with the readonly? method in activerecord classes. It appears that anything fetched with a call to joins is being set to readonly and throws this error

ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord

For instance:

# fine 
User.first.readonly?
User.first.save
# not fine
User.joins(:memberships).first.readonly?
# false
User.joins(:memberships).first.save
# ActiveRecord::ReadOnlyRecord

According to the Rails documentation this will be set to false for "Records loaded through joins with piggy-back attributes."

As far as I'm aware, we're not including any piggy-back attributes here.

I can forcibly circumvent this restriction, but it feels like I'm hacking through the system unnecessarily.

user = User.joins(:memberships).first
User.instance_variable_set(:@readonly, false)
user.save

Does anyone know why joins is returning readonly items? Can I prevent this? (I'm not trying to select any attributes from related objects).

I'm using Ruby on Rails version 3.2.22.5, It looks like this has been a change in behavior from an earlier version of Rails 3.

Aucun commentaire:

Enregistrer un commentaire