更正:你可以做这样的事情
render json: @teams.to_json(:except => [:created_at, :updated_at], :include => { :stadiums => { :except => [:created_at, :updated_at]}, ... })
有这样做不遍历相关模型,获得的属性散列并选择所需的属性,没有简单的方法。
此类用例通常使用json模板DSL(如jbuilder或rabl)进行优雅地解决。
为了说明这一点使用的JBuilder:
Jbuilder.encode do |json|
json.array! @teams do |team|
json.name team.name
json.stadiums team.stadiums do |stadium|
json.name stadium.name
# Other relevant attributes from stadium
end
# Likewise for scores, links, rounds
end
end
将产生输出为:
[{
name: "someteamname",
stadiums: {
name: "stadiumname"
},
...
}, {...},...]
如果您发现您的使用情况下,这太冗长,如@liamneesonsarmsauce已经在指出另一种解决方案是使用ActiveModel Serializers
使用此方法,您可以为每个模型指定序列化程序类,列出a降低了属性,这将成为json响应的一部分。例如,
class TeamSerializer < ActiveModel::Serializer
attributes :id, :name # Whitelisted attributes
has_many :stadiums
has_many :scores
has_many :links
has_many :rounds
end
您也可以为相关模型定义类似的序列化器。
由于关联是以一种对Rails开发人员熟悉的方式进行无缝处理的,除非您需要对生成的json响应进行大量定制,这是一种更简洁的方法。
此外,我不喜欢使用jbuilder或rabl,而更喜欢使用https://github.com/rails-api/active_model_serializers Active Model Serializer。 – dasnixon
'{include:{stadiums:{except::foo}}}''语法不适用于'except',只有'methods'这样的东西?我目前无法测试。 –
@DaveNewton这是可行的。看起来我有点不小心。 – lorefnon