Пишу стажировочный проект, имеем такой сериалайзер:
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
Помогите, не знаю куда копать дальше