开发者

How do I use ActiveRecord's .build method and pass in attributes in JSON format?

I'm pulling records off from a message queue in JSON format and want to use ActiveRecord's .build method if I can to simply pass in the record and build the object.

How do I do this? Are there any downs开发者_如何学JAVAides to this approach?


In principle you can use YourModel.new.from_json(json_string) but how that behaves depends on the boolean ActiveModel::Base.include_root_in_json. Set that to false first if your json is a straightforward hash/object or leave it as true (the default) if your json is the kind of nested hash produced by to_json (again, by default).

All that method does is decode the json to a hash and calls self.attributes = hash, so you could just as easily do that yourself.

With respect to downsides, there really aren't any specific to this process. You're essentially doing the same thing you'd do in a standard create controller method, replete with validations, attr_accessible restrictions and so on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜