开发者

Custom to_json method not being called in Rails app

开发者 https://www.devze.com 2023-01-06 07:13 出处:网络
I have a Ruby on Rails application that I\'m working on an API for an associated iPhone application. I have overwritten the to_json method of my Item model to return some custom information from the

I have a Ruby on Rails application that I'm working on an API for an associated iPhone application.

I have overwritten the to_json method of my Item model to return some custom information from the API request that I'll need in the iPhone app.

However, when I use the built-in rails to_json method and include my Item model as an associated parameter, my Item#to_json method is not called, and just the default to_json on the AR object is called.

See the following code (@api_user is a User model object)

    render :json => @api_user.to_json( :include => { :friends => { :include => :items, :except => :api_token } } )

I'm including the friends association which is in turn including the items assocation, but the default to_json on Item is being called, not my custom to_json.

What am I missing?

Here is my Item#to_json开发者_运维问答 method

  def to_json(options={})
{
  :id => self.id,
  :name => name,
  :description => description,
  :url => url,
  :quantity => quantity,
  :price_range_raw => price_range,
  :price_range => human_readable_price_range( price_range ),
  :can_be_purchased => can_be_purchased?,
  :completely_purchased => completely_purchased?,
  :remaining_qty => remaining_quantity,
  :thumb_photo_url => photo.url(:thumb),
  :small_photo_url => photo.url(:small),
  :large_photo_url => photo.url(:large),
  :priority_raw => priority,
  :priority => human_readable_priority( priority )
}.to_json

end

No other models have the #to_json method overriden


Are you using Devise? If so, they overwrite the to_json and to_xml method (thanks, guys).

From the Devise source:

  %w(to_xml to_json).each do |method|
    class_eval <<-RUBY, __FILE__, __LINE__
      def #{method}(options={})
        if self.class.respond_to?(:accessible_attributes)
          options = { :only => self.class.accessible_attributes.to_a }.merge(options || {})
          super(options)
        else
          super
        end
      end
    RUBY
  end


Isn't there a more straightforward method to override the to_json method? Using Devise doesn't address the general issue. There are plenty of reasons why I might wish to choose to NOT marshal out some attributes of a particular object, thus requiring a custom method.

0

精彩评论

暂无评论...
验证码 换一张
取 消