想象一下,我有以下模特:
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
?
答案 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) }
为什么不试试这个。让production_currency
从自己的关联中收集所需的信息。像
def production_currency
currency = self.voice.currency
ip = self.voice.ip
end
和
:productions => {:methods => :production_currency}