简体   繁体   中英

Render json with a condition in rails

I am working on serializers. I want to display some jobs with attribute cancelled=true . I tried render json: @jobs, :only => [:cancelled] , but its only displaying the jobs with cancelled attribute. How can I filter the jobs? I also tried json: @jobs, :only => [:cancelled =="true"] , but it's not working.

I tried it in serializer too. This is my serializer:

module V1
  module Jobs
    class CancelledJobSerializer < ActiveModel::Serializer
      attribute :id, if: :id?
      attribute :cancelled, if: :cancelled?
      def cancelled?
        true if object.cancelled
      end
      def id?
        true if object.cancelled
      end
    end
  end
end

and it returns

{},
{},
{},
{},
{},
{},
{},
{},
{},
{"cancelled":true }

Is there anyway to remove those parentheses?

Add a scope to the Job model so it can return canceled (cancelled) jobs

scope :cancelled, -> { where(cancelled: true) }

And then in your controller

@cancelled_jobs = Job.cancelled
render json: @cancelled_jobs

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