Reputation: 6627
If you use joins
in an ARel scope, the result becomes read-only (i.e. you cannot update any of the records you get back). If you would not like the result to be read-only, you just chain readonly(false)
to the scope, e.g.
User.joins(:orders).where(:orders => { :state => 'completed' }).readonly(false)
But I'm guessing that there is a reason why the join-scopes by default are read-only. What is the reason behind setting the results to read-only?
Upvotes: 11
Views: 1604
Reputation:
Interesting question. I was googling around.....With a joins query, you're getting back a single record with the User + order table attributes. If you tried to update one of the attributes (say "order_num") in the order table instead of the User table, the update statement to the User table wouldn't be able to find order_num and would crash. So the join-scopes are read-only by default to prevent that from happening.
References:
1) http://blog.ethanvizitei.com/2009/05/joins-and-namedscopes-in-activerecord.html
2) Proper way to prevent ActiveRecord::ReadOnlyRecord?
Upvotes: 1