如何将模型中的两个字段渲染为 JSON?
How do I render only two fields from my model as JSON?
我有一个 Rails 5 应用程序和一个具有许多属性的 Person 模型,包括
id
name
我想从我找到的人员列表中呈现这两个属性。我试过这个
format.js {
render :json => @people.to_json(include: [:id, :name])
}
其中“@people”是一个 Person 对象数组,但上面的结果是
undefined method `serializable_hash' for 16:Integer
错误。从我的 Person 模型中只呈现两个字段的正确方法是什么?
您应该使用 only:
而不是 include:
format.js {
render :json => @people.to_json(only: [:id, :name])
}
虽然 only
只会为您提供该模型所需的属性,但 include
意味着包括模型的其他关联! (关联为 belong_to
或 has_many
等)
无论如何,还有另一种方法可以在模型查询中使用 select
获得相同的结果。
@poeple = Person.select(:id, :name).where(....)
然后只是 return to_json
-> 你不需要排除任何属性,因为你首先只得到你想要的属性。
** 只有在其他情况下不需要其他属性时,第二种方法才有用。例如,如果你想 return 模型的完整属性列表,如果它不是 json
我有一个 Rails 5 应用程序和一个具有许多属性的 Person 模型,包括
id
name
我想从我找到的人员列表中呈现这两个属性。我试过这个
format.js {
render :json => @people.to_json(include: [:id, :name])
}
其中“@people”是一个 Person 对象数组,但上面的结果是
undefined method `serializable_hash' for 16:Integer
错误。从我的 Person 模型中只呈现两个字段的正确方法是什么?
您应该使用 only:
而不是 include:
format.js {
render :json => @people.to_json(only: [:id, :name])
}
虽然 only
只会为您提供该模型所需的属性,但 include
意味着包括模型的其他关联! (关联为 belong_to
或 has_many
等)
无论如何,还有另一种方法可以在模型查询中使用 select
获得相同的结果。
@poeple = Person.select(:id, :name).where(....)
然后只是 return to_json
-> 你不需要排除任何属性,因为你首先只得到你想要的属性。
** 只有在其他情况下不需要其他属性时,第二种方法才有用。例如,如果你想 return 模型的完整属性列表,如果它不是 json