activerecord - Rails as_json with two unrelated models -


Looking at two models and controllers:

Apple class apple and lieutenant; ActiveRecord :: Base is_to: not_oranges ... def as_json (options = {}) opts = {: include = & gt; [: Not_oranges]} Super end (options.reverse_merge! Opts) End End

Orange

  Class oranges < ActiveRecord :: Base is_to: not_apples ... def as_json (option = {}) opts = {: include = & gt; [: Not_apples]} Super (options.reverse_merge! Opts) End End   

Search Controller

  Class SearchController & lt; ApplicationController a = Apple Search Consulting [: Q] O - Orange Search Parameter [: Q] @ ruits = {: apple => A ,: orange = & gt; O} answer_ to do | Format | Format.json {Render: Jason = & gt; As you can see, both models are not completely unrelated and they both have different :  in their  as_json  are included in the options.   Definitions  

Expected all actions as if the search query kills only apples or hit orange, but both objects are not empty once:

  undefined method `not_apples' For # & lt; Oranges: 0x00000004af8cd8 & gt;   

Either both as_json definitions are being merged, or overriding Oranges.as_json Apples .as_json .

Is this the expected behavior? Is there any clean way around without using anything like RABL? I think it would be more for my needs.

The code in the pseudo code looks like code as_json

  def as_json (option = {}) hash [collect {| Key, element | [Key.to_s, element.as_json (option)]}]   

But your element is modifying the option argument that you have Have done Hash is unaware of this and therefore the modified option hash for as json passes.

It is usually a good idea to not move the arguments passed by you, it is fine, it is fine. I type your method again as

  def as_json (options = {}) = defaults = {: include = & gt; : Not_apples} super (defaults.merge (options)) end    

Comments

Popular posts from this blog

Python SQLAlchemy:AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'schema' -

java - How not to audit a join table and related entities using Hibernate Envers? -

mongodb - CakePHP paginator ignoring order, but only for certain values -