如何使用as_json在关联中使用方法

时间:2016-03-07 16:19:27

标签: ruby-on-rails ruby ruby-on-rails-4

想象一下,我有以下模特:

class Voice
  include Mongoid::Document
  ...
  has_and_belongs_to_many :productions
  ...
  def define_user_currency
  ...
  end
end

class Production
  include Mongoid::Document
  ...
  has_and_belongs_to_many :voices
  ...
  def production_currency
  ...
  end
end

我希望获得包含所有作品的所有Voices,并在每个define_user_currency上调用Voice以及在每个制作中调用production_currency。我尝试了以下内容(我在Voice上添加了此方法):

def_custom_format
  self.as_json(
    method: self.define_user_currency(currency, ip),
    include: [:builder_types, :voice_types, :preferences, :languages, :productions => {:methods => production_currency(currency, ip)}],
    except: [:avatar_content_type, :avatar_file_size, :avatar_file_name, :avatar_fingerprint, :avatar_updated_at, :voice_content_type, :voice_file_size, :voice_fingerprint, 
    :voice_updated_at, :artist_id, :price_per_word_GBP, :price_per_word_EUR, :price_per_word_USD, :price_GBP, :price_EUR, :price_USD, :categories_name, :category_ids, :production_ids, 
    :language_ids, :preference_ids, :voice_type_ids, :builder_type_ids]
  )
end

但是Production不在Voice范围内,而是Undefined method production_currency。如果我尝试include: [:builder_types, :voice_types, :preferences, :languages, :productions => {:methods => self.production_currency(currency, ip)}],,我会得到相同的结果。

如何在每次制作中应用production_method

1 个答案:

答案 0 :(得分:1)

如果您的方法production_currency(currency, ip)没有采用任何参数,那么这是可能的。由于无法发送逗号分隔值(如

),因此无法发送结果
methods: :production_currency, currency, ip
# or
methods: "production_currency(#{currency},#{ip})"

参见代码

 Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }

https://github.com/rails/rails/blob/5b368010f64106f7b87a4306b41adcefa856ab67/activemodel/lib/active_model/serialization.rb#L110

为什么不试试这个。让production_currency从自己的关联中收集所需的信息。像

def production_currency
  currency = self.voice.currency
  ip = self.voice.ip
end

:productions => {:methods => :production_currency}