2016-03-07 40 views
0

想象我有以下型号:如何使用as_json到一个联合中使用的方法

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包括所有的制作和调用每个Voicedefine_user_currency以及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

如果您的方法production_currency(currency, ip)没有采用任何参数,将是可能的。它不能发送aruguements因为没有办法送样

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} 
+0

我照你建议(除去参数形成的方法),并再次尝试,但所发生的事情是我没有错误,但没有发生任何(我没有收到任何产品数据,就像我没有包括':productions' – WagnerMatosUK

+0

可能没有这个关系的生产数据 – illusionist

+0

说实话,经过相当多的斗争后,我发现了我需要指出你几乎是正确的,解决方法是使用一个没有参数的方法,但是结构略有不同:'include:{productions:{met hod:production_currency}}' – WagnerMatosUK

相关问题