Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 scoped finds giving ActiveRecord::ReadOnlyRecord

I am upgrading a Rails application from 2.3.10 to 3.0.4 and am running into an issue with updating models in my controller. I have been "scoping" model finds in order to prevent users from updating objects that don't belong to them. It works as expected in 2.3, but I get an ActiveRecord::ReadOnlyRecord error with update_attributes in Rails 3.

What is the right way to do this in Rails 3?

Project controller:

def update
  @project = current_user.projects.find(params[:id])

  if @project.update_attributes(params[:project])
    # saved
  else
    # not saved
  end
end
like image 554
Peter Brown Avatar asked Feb 15 '11 13:02

Peter Brown


2 Answers

It turns out it was related to using scopes to impersonate active record associations. I was able to fix it by adding .readonly(false) to my scopes.

like image 95
Peter Brown Avatar answered Oct 05 '22 22:10

Peter Brown


One possible solution is create new file config/active_record_monkey_patch.rb and add following content in it.

module ReadOnlyFalse
  def self.included(base)
    base.class_eval do
      def readonly?
        false
      end
    end
  end
end

ActiveRecord::Base.send(:include, ReadOnlyFalse)

above code work for all models readonly(false).

like image 22
waqas ali Avatar answered Oct 05 '22 23:10

waqas ali