如何将参数的默认反序列化覆盖为模型对象?换句话说,如何让 Rails 用蛇案例数据库理解骆驼案例 JSON?
示例:我收到Foo带有字段的 params 对象,fooBar我希望我的Foo模型理解fooBar实际上是数据库字段foo_bar。
"Foo": {
"fooBar": "hello" /* fooBar is database field foo_bar */
}
class Foo < ActiveRecord::Base
attr_accessible :foo_bar
end
class FoosController < ApplicationController
def new
@foo = Foo.new(params[:foo])
end
Foo.new(params[:foo])假设params[:foo]包含foo_bar. 而是params[:foo]包含fooBar(在我的情况下params包含 JSON 数据)。
我想要一种干净的方式来处理这种情况,就像模型可以覆盖一样as_json:
class Foo < ActiveRecord::Base
attr_accessible :foo_bar, :another_field
def as_json(options = nil)
{
fooBar: foo_bar,
anotherField: another_field
}
end
end
from_jsonActiveModel 内部有一个方法,但在Foo.new(params[:foo])运行时不会调用它。
我已经读过好几次了,initialize从模型对象中覆盖是一个糟糕的主意。