[英]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.first
正常工作,它正确地返回数据但是当我尝试使用相同的东西时:include
在to_json
方法中:include
它失败并出现以下错误:
@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; to_json
方法具有相同的:include
语法作为find; I don't understand why it is not working. 我不明白为什么它不起作用。
如果其他人遇到了我所做的一个奇怪的相关问题...当你试图包含一个未在模型上定义的关联时, to_json
也会返回此错误。
I think the to_json
:include syntax is a little different. 我认为to_json
:include语法有点不同。
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. 尝试在单个to_json调用中混合第一和第二顺序关系时出现此错误。 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. 它抛出了“未定义的方法`宏'为nil:NilClass”异常。
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. Array适用于单阶关系,但对于二阶关系,包含对象需要是Hash。
I had this problem when i overrided the as_json function 当我重写as_json函数时,我遇到了这个问题
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. 出于某种原因,当你在没有参数的数组上调用as_json或to_json时,选项变为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.