0

Here is my model:

class ServiceRequest
  include ActiveModel::Model
  include ActiveModel::Validations
  include ActiveModel::Serialization
  extend ActiveModel::Naming

  attr_accessor :first_name, :last_name, :prefix, :contact_email, :phone_number,
                :address, :address2, :city, :state, :zip_code, :country,
                :address_type, :troubleshooting_reference, :line_items, :id

  validates_presence_of :first_name, :last_name, :contact_email, :phone_number,
                        :address, :city, :state, :zip_code, :country, :address_type,
                        :troubleshooting_reference

  validate :check_line_items

  def initialize(attributes = {})
    super
    @errors = ActiveModel::Errors.new(self)
    @api_response = nil
    @id = nil
  end

  def check_line_items
    @line_items.each do |item|
      errors.add(:base, "#{item.errors.full_messages.join}") unless item.valid?
    end
  end

  def line_items_attributes=(attributes)
    @line_items ||= []
    attributes.each do |i, params|
      @line_items.push(LineItem.new(params))
    end
  end

  def save
    conn = Faraday.new(url: "#{Figaro.env.arciplex_url}") do |faraday|
      faraday.request :url_encoded
      faraday.response :logger
      faraday.adapter  Faraday.default_adapter
    end

    @api_response = conn.post do |req|
      req.url "/api/v1/service_requests?token=#{Figaro.env.api_token}"
      req.headers['Content-Type'] = 'application/json'
      req.body = self.to_json
    end

    validate!
  end

  def validate!
    # If successful creation, do nothing
    unless [200, 201].include?(@api_response.status)
      Rails.logger.debug(@api_response.inspect)
      errors.add(:base, @api_response.body)
      return false
    else
      Rails.logger.debug(JSON.parse(@api_response.body))
      @id = JSON.parse(@api_response.body)["service_request_id"]
      return true
    end
  end

  def to_json(options = {})
    options[:except] ||= [:id, :api_response, :errors]
    super(options)
  end

end

When I call self.to_json even though I am not including the :id, :api_response and :errors, they still appear in the jsonified object. I'm doing something wrong (obviously), but I can't figure out why it's not working.

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189
  • Is `options` what you expect it to be when you call `super(options)`? Is the `super` version of `to_json` coming from `ActiveModel::Serialization` or somewhere else? – mu is too short Jul 22 '14 at 21:22
  • It should be coming from `ActiveModel::Serialization`. Let me do some debugging – dennismonsewicz Jul 23 '14 at 13:47
  • I ask because I'm not very familiar with this stuff and I'm wondering if the `to_json` you end up `super`-ing to understands all the `options` you're expecting it to. – mu is too short Jul 23 '14 at 16:29

0 Answers0