在 fast_jsonapi 中将 current_user 和链接一起传递,在 rails 中
Pass current_user and links together in fast_jsonapi, in rails
Rails 版本:6.0.0
Ruby 版本:2.6.3
控制器
render json: AreaSerializer.new(
Area.all, paginate(pagy), params: { current_user: current_user }
), status: ok
序列化器
attributes :nodes do |area, params|
...
end
错误:
ArgumentError (wrong number of arguments (given 3, expected 1..2)):
使用这样的东西:
render json: AreaSerializer.new(
Area.all,
{ params: { paginate: paginate(pagy), current_user: @current_user } }
), status: ok
序列化器
attributes :nodes do |area, params|
...
params[:current_user]
params[:paginate]
...
end
我尝试了另一种方法,它起作用了,
在控制器中
areas = Area.all
options = {
links: paginate(pagy),
params: { current_user: @current_user }
}
render json: AreaSerializer.new(areas, options),
status: ok
在序列化器中
attributes :nodes do |area, params|
area.users.where.not(id: params[:current_user].id)
end
并且链接键在 Serializer 中自动呈现。
前端收到的示例输出:
{
data: [
{},
{} // areas hash
],
links: {
first: "",
last: "",
}
}
Rails 版本:6.0.0 Ruby 版本:2.6.3
控制器
render json: AreaSerializer.new(
Area.all, paginate(pagy), params: { current_user: current_user }
), status: ok
序列化器
attributes :nodes do |area, params|
...
end
错误:
ArgumentError (wrong number of arguments (given 3, expected 1..2)):
使用这样的东西:
render json: AreaSerializer.new(
Area.all,
{ params: { paginate: paginate(pagy), current_user: @current_user } }
), status: ok
序列化器
attributes :nodes do |area, params|
...
params[:current_user]
params[:paginate]
...
end
我尝试了另一种方法,它起作用了,
在控制器中
areas = Area.all
options = {
links: paginate(pagy),
params: { current_user: @current_user }
}
render json: AreaSerializer.new(areas, options),
status: ok
在序列化器中
attributes :nodes do |area, params|
area.users.where.not(id: params[:current_user].id)
end
并且链接键在 Serializer 中自动呈现。
前端收到的示例输出:
{
data: [
{},
{} // areas hash
],
links: {
first: "",
last: "",
}
}