简体   繁体   中英

ActiveModel Serializer not working for function

I am using ActiveModelSerialziers in my Rails API and it works like a charm but 1 of my functions seems to override it, and only returns my model (without any of the associations). The same model returns properly if a different function is called.

  def getClient
    type = params[:type]

    if type == 'user'
      @client = Client.find_by(user_id: params[:id])
    else
      @client = Client.find_by(id: params[:id])
    end


    render json: { success: true, response: @client }
  end

only returns the client without the associations and the serializer is:

class API::ClientSerializer < ActiveModel::Serializer

    attributes :name, :age, :address

    belongs_to :user
    has_many :check_ins
    has_many :client_docs
    has_many :payments
end

While the same model ( Client ) returns properly (with associations) when the following function is called:

  def show
    model_name = params[:model].classify
    item = model_name.constantize.find_by(id: params[:id])

    render json: item, status: :ok
  end

Why might this happen?

您在rander语句中缺少适配器::json:

render json: item, adapter: :json, status: :ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM