0

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.

AJFaraday
  • 2,411
  • 1
  • 16
  • 39
  • FWIW, Rails 3.2 is over 5 years old. When it was released, Siri was brand new, Kim Jong Il was still the head of North Korea, and Lyft hadn't launched yet. It's no longer supported by the Rails team and can no longer be considered secure. If you still experience this behavior on a newer version of Rails, please update or ask a new question. – coreyward Jun 07 '17 at 17:36
  • @coreyward I'm so glad you felt able to provide that information. I didn't have a clue about any of it, because I live in a cave. – AJFaraday Jun 07 '17 at 17:38
  • Ah, so you're also aware that [this was fixed here](https://github.com/rails/rails/pull/10769) and is available for you to download for free because some other people contributed their time to solving it for you, you just have to download and use it. But hey, keep being sarcastic and insisting *we're* the jerks for not doing everything for you. – coreyward Jun 07 '17 at 21:54
  • Possible duplicate of [Proper way to prevent ActiveRecord::ReadOnlyRecord?](https://stackoverflow.com/questions/7667052/proper-way-to-prevent-activerecordreadonlyrecord) – coreyward Jun 07 '17 at 21:56
  • I'm stuck with older versions of rails in my position, I do push to upgrade but unfortunately progress is slow. Good to know this isn't expected behaviour, tho. – AJFaraday Jun 07 '17 at 21:56

1 Answers1

0

Try using includes instead of joins, it's better and faster.

User.includes(:memberships).first
Jaye Hernandez
  • 483
  • 1
  • 4
  • 13