考虑以下show.json.jbuilder
模板:
json.user do |json|
json.extract! @user, :id, :username, :email, :created_at, :avatar
end
json.policies do |json|
json.array!(@policies) do |policy|
json.extract! policy, :id, :title, :cached_votes_score
end
end
json.liked do |json|
json.array!(@liked) do |policy|
json.extract! policy, :id, :title, :cached_votes_score
end
end
json.disliked do |json|
json.array!(@disliked) do |policy|
json.extract! policy, :id, :title, :cached_votes_score
end
end
是否可以将它们分成四个不同的模板,然后将它们包含在show
模板中?类似的东西:
include template_user
include template_policies
include template_liked
include template_disliked
如果无法做到这一点,那么创建更多模块化jbuilder代码有哪些替代方案?我发现我的jbuilder代码非常干。
答案 0 :(得分:5)
是。有可能。将文件拆分为:
_user.json.jbuilder
json.user do |json|
json.extract! @user, :id, :username, :email, :created_at, :avatar
end
_policies.json.jbuilder
json.policies do |json|
json.array!(@policies) do |policy|
json.extract! policy, :id, :title, :cached_votes_score
end
end
_liked.json.jbuilder
json.liked do |json|
json.array!(@liked) do |policy|
json.extract! policy, :id, :title, :cached_votes_score
end
end
_disliked.json.jbuilder
json.disliked do |json|
json.array!(@disliked) do |policy|
json.extract! policy, :id, :title, :cached_votes_score
end
end
然后你可以简单地加入:
show.json.jbuilder
json.partial! 'user'
json.partial! 'policies'
json.partial! 'liked'
json.partial! 'disliked'
但我建议稍微改进它们并使用局部变量编写它们,所以:
_user.json.jbuilder
json.user do |json|
json.extract! user, :id, :username, :email, :created_at, :avatar
end
并且包含它将用户作为参数传递:
json.partial! 'user', user: @user