10

I have the following code

@asset = Asset.first(
  :include => [
    :asset_statuses => [
      :asset_status_name, 
      {:asset_location => [
        {:asset_floor => :asset_building}
      ]}
    ],
    :asset_type => [
      :asset_category => :asset_department
    ]
  ],

(probably not the best DB table desing but that's what I have to use)

The Asset.first works correctly and it brings back the data correctly but when I try to use the same :include in the to_json method it fails with the followings error:

@asset.to_json( 
  :include => [
    :asset_statuses => [
      :asset_status_name,
      {:asset_location => [
        {:asset_floor => :asset_building}
      ]}
    ],
    :asset_type => [
      :asset_category => :asset_department]
    ] 
)

NoMethodError (undefined method `macro' for nil:NilClass):

The to_json method has the same :include syntax as find; I don't understand why it is not working.

4 Answers 4

23

In case anyone else runs into a bizarre related issue that I did...to_json will also return this error when you try to include an association that is not defined on the model.

Sign up to request clarification or add additional context in comments.

Comments

8

I think the to_json :include syntax is a little different.

I usually do

@asset.to_json(:include => { :asset_statuses => {
                             :include => :asset_status_name}})

(and start with a small one then add all of the other stuff. annoying schema!)

Comments

7

I got this error when trying to mix 1st and 2nd order relationships in a single to_json call. Here is what I originally had:

render :json => @reports.to_json(:include => 
   [:report_type, :organisation, :analysis => {:include => :upload}]

which throws the "undefined method `macro' for nil:NilClass" exception above.

Here's how I fixed it:

render :json => @reports.to_json(:include => 
   {:report_type => {}, :organisation => {}, 
    :analysis => {:include => {:upload => {}}}})

The Array will work for single-order relationships, but for second order relationships, the containing object needs to be a Hash.

Comments

2

I had this problem when i overrided the as_json function

def as_json(options={})
  if options[:admin] 
    super(:methods => [:url_thumb] )
  else
    super(options.merge( :only => :id ))
  end
end

for some reason when you call the as_json or to_json on an array with no arguments the options became nil.

The fix is:

def as_json(options={})
  options = {} if options.nil?
  if options[:admin] 
    super(:methods => [:url_thumb] )
  else
    super(options.merge( :only => :id ))
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.