ActiveResource MassAssignmentSecurity error with T

2019-07-20 07:22发布

I am trying to implement basic CRUD operations with ActiveResource on a rails model. The documentation says to make a sub-class of ActiveResource::Base and then set self.site.

This works well UNTIL I try to update an existing record that has been fetched. The error I see is a 'MassAssignmentSecurity::Error' which appears when I call the 'save()' method on my ActiveResource object due to the created_at and updated_at fields are not accessible.

I found if mark those fields with attr_accessible on my model class it works ok, but that seems quite an insecure and pretty poor solution.
Below shows an example of the issue:

rails new TestApp
cd TestApp
rails generate scaffold User first:string last:string
rake db:create
rake db:migrate
rails server

On a different terminal tab I use:

irb
require 'active_resource'
class User < ActiveResource::Base
self.site = 'http://localhost:3000'
end
u = User.new()
u.first = 'John'
u.last = 'Shine'
u.save()
#This saves ok
nu = User.find(1)
nu.first = 'Geoff'
nu.save() 
#This never works

Is there a better solution to this?

1条回答
太酷不给撩
2楼-- · 2019-07-20 07:37

Assuming you want to discard the Timestamp fields and have rails create them automatically (as normal) I would get the data from a new json/xml template inside the app which doe not include the Timestamp fields.

Also assuming you have access to the app which is providing the data you could add something like the below to your rails model to test, it overrides (could call it 'uses') the as_json method for the json template.

def as_json(options = {})
  super(:except => [:created_at, :updated_at])
end

This will update the timestamp fileds by the rails server itself.

Alternatively you should have a look at RABL and jbuilder as both are great options.

查看更多
登录 后发表回答