Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to override default deserialization of params to model object?
    primarykey
    data
    text
    <p>How to override default deserialization of params to model object? In other words, how to make Rails understand camel case JSON with a snake case database?</p> <p>Example: I receive params <code>Foo</code> object with a field <code>fooBar</code> and I want my <code>Foo</code> model to understand <code>fooBar</code> is in fact database field <code>foo_bar</code>.</p> <pre><code>"Foo": { "fooBar": "hello" /* fooBar is database field foo_bar */ } </code></pre> <pre><code>class Foo &lt; ActiveRecord::Base attr_accessible :foo_bar end class FoosController &lt; ApplicationController def new @foo = Foo.new(params[:foo]) end </code></pre> <p><code>Foo.new(params[:foo])</code> assumes <code>params[:foo]</code> contains <code>foo_bar</code>. Instead <code>params[:foo]</code> contains <code>fooBar</code> (in my case <code>params</code> contains JSON data).</p> <p>I would like a clean way to handle this case, the same way a model can override <code>as_json</code>:</p> <pre><code>class Foo &lt; ActiveRecord::Base attr_accessible :foo_bar, :another_field def as_json(options = nil) { fooBar: foo_bar, anotherField: another_field } end end </code></pre> <p>There is a <a href="http://apidock.com/rails/ActiveModel/Serializers/JSON/from_json" rel="nofollow"><code>from_json</code> method inside ActiveModel</a> but it is not called when <code>Foo.new(params[:foo])</code> is run.</p> <p>I've read several times that overriding <code>initialize</code> from a model object is a terrible idea.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload