我正在写一个实习项目,我们有以下序列化程序:
class PhotopostSerializer < ActiveModel::Serializer
attributes :id, :content, :picture, :comments_count, :rating_count, :liked_by_current_user
belongs_to :user
has_many :comments do
comments = []
object.comments.each do |comment|
comments << { id: comment.id, content: comment.content, user: { id: comment.user.id,
first_name: comment.user.first_name,
last_name: comment.user.last_name,
image: comment.user.image } }
end
comments
end
def liked_by_current_user
object.rating.pluck(:user_id).include?(instance_options[:current_user])
end
end
在控制器中,我们有 index 和 show 方法,每个方法都需要自己的评论数(索引中只有 3 个,都在 show 中。)
试图创建几个继承自上述类的类,但给出错误
undefined method `model_name' for Photopost::ActiveRecord_Relation:Class(在控制器中指定序列化程序时)或superclass mismatch for class PhotopostShowSerializer(在删除序列化程序后第一次请求方法时)
def index
photoposts = Photopost.custom_order(params[:order_by], params[:order_type])
render json: photoposts, current_user: api_user.id, status: :ok
end
def show
photopost = Photopost.find(params[:id])
if photopost.moderating?
if photopost.user == api_user
render json: { message: "Post with id #{params[:id]} on moderation" }
else
raise ActiveRecord::RecordNotFound
end
else
render json: photopost, status: :ok, current_user: @api_user.id
end
rescue ActiveRecord::RecordNotFound
render json: { message: "Post with id #{params[:id]} is not found" }, status: :not_found
end
帮助,我不知道在哪里进一步挖掘