简体   繁体   中英

Ruby on Rails to_json problem with :include

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.

如果其他人遇到了我所做的一个奇怪的相关问题...当你试图包含一个未在模型上定义的关联时, to_json也会返回此错误。

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!)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM