活动模型序列化程序未使用正确的属性进行响应
Active Model Serializer not responding with the correct attributes
我正在使用 active model serialiazer
进行 rails-api
项目。但不幸的是,它没有按预期工作。这是我的 V1::HuntsController
class V1::HuntsController < V1::MainController
def index
render json: Hunt.all
end
end
我的 hunts 序列化器看起来像这样
class HuntSerializer < ActiveModel::Serializer
belongs_to :user
attributes :id,:title,:picture_url,:clue
private
def picture_url
object.picture.url
end
end
但在我的 response
中,我从 hunt
获取所有属性。我也尝试显式定义序列化程序以避免版本控制问题。
render json: {data: Hunt.all } ,each_serializer: HuntSerializer
但似乎没有任何效果。在我看到的日志中,
[active_model_serializers] Rendered V1::HuntSerializer with Hash (32.36ms)
这里发生了什么。任何帮助将不胜感激。
尝试
render json: Hunt.all, each_serializer: HuntSerializer
(不需要数据根)
然后为了验证序列化程序是否被命中,在 picture_url 函数的主体中放置一个 byebug
。如果 byebug
被击中,你确实在使用你的序列化器。 (必须在 gem 文件中包含 gem byebug)
我正在使用 active model serialiazer
进行 rails-api
项目。但不幸的是,它没有按预期工作。这是我的 V1::HuntsController
class V1::HuntsController < V1::MainController
def index
render json: Hunt.all
end
end
我的 hunts 序列化器看起来像这样
class HuntSerializer < ActiveModel::Serializer
belongs_to :user
attributes :id,:title,:picture_url,:clue
private
def picture_url
object.picture.url
end
end
但在我的 response
中,我从 hunt
获取所有属性。我也尝试显式定义序列化程序以避免版本控制问题。
render json: {data: Hunt.all } ,each_serializer: HuntSerializer
但似乎没有任何效果。在我看到的日志中,
[active_model_serializers] Rendered V1::HuntSerializer with Hash (32.36ms)
这里发生了什么。任何帮助将不胜感激。
尝试
render json: Hunt.all, each_serializer: HuntSerializer
(不需要数据根)
然后为了验证序列化程序是否被命中,在 picture_url 函数的主体中放置一个 byebug
。如果 byebug
被击中,你确实在使用你的序列化器。 (必须在 gem 文件中包含 gem byebug)