2

When I try to update and save ActiveResource I am getting following error.

on console

> m = Machine.first
 => #<Machine:0xb07a0d4 @attributes={"created_at"=>"2013-04-22T09:13:56Z", "id"=>1, "name"=>"laptop", "updated_at"=>"2013-04-22T09:13:56Z"}, @prefix_options={}, @persisted=true>

> m.name = 'mouse'
 => "mouse"

> m.save
ActiveResource::ServerError: Failed.  Response code = 500.  Response message = Internal Server Error

on server

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: created_at, id, updated_at):
  app/controllers/machines_controller.rb:62:in `block in update'
  app/controllers/machines_controller.rb:61:in `update'

Here is ActiveResource model

class Machine < ActiveResource::Base
  self.site = 'http://localhost:3000'
end

Here is ActiveRecord model

class Machine < ActiveRecord::Base
  attr_accessible :name
end
Amit Patel
  • 15,609
  • 18
  • 68
  • 106
  • I think something went wrong with rails instalation. Try to reinstall it: `gem uninstall rails && gem install rails` – Eraden Apr 22 '13 at 12:01
  • @Eraden it doesn't work either. – Amit Patel Apr 22 '13 at 17:25
  • 1
    http://stackoverflow.com/questions/14812598/activeresource-massassignmentsecurity-error-with-timestamp-fields – Eraden Apr 23 '13 at 06:58
  • It worked. But the problem is that I can't change codebase of the API I am accessing. ActiveResource should have such configuration to skip some of the attributes. – Amit Patel Apr 23 '13 at 08:56
  • Maybe try use this: http://apidock.com/rails/ActiveResource/Base/schema/class – Eraden Apr 23 '13 at 10:53
  • @Eraden, it doesn't work either. Keep on getting same error. – Amit Patel Apr 30 '13 at 07:09
  • 1
    Last I can suggest is to override in this class (ActiveResource::Base or child class) method: as_json. When you do this request you can skip created_at and updated_at. ActiveResource::Base include ActiveRecord::Serializers. I don't known other way and sorry if I'm wrong, there is no other way. Here is API https://github.com/rails/rails/blob/c2193c11ad215d3a2d7d35960630b3e1902a5082/activeresource/lib/active_resource/base.rb#L1381 and there aren't any method that give you possibility to configuration other than schema (but if you need those date you can't use this). – Eraden Apr 30 '13 at 21:04
  • @Eraden, It worked. Thanks. But wouldn't you think there should be more elegant solution in ActiveResource itself for common fields like id, created_at and updated_at? – Amit Patel May 03 '13 at 05:24
  • I think yes but I can't find anything better. You can write ticket for rails developers. If I'm wrong they are writing you better solution (I hope) or, if I'm right maybe they're solve the problem. Most developers won't wrote anything to developers. Sometimes they should. – Eraden May 06 '13 at 13:28

0 Answers0