Rails (4.0.0)可以做到这一点——我们目前有两种方法:
1. SQL“别名”列
Rails 为 has_many 确定范围:通过访问额外数据
#Images
has_many :image_messages, :class_name => 'ImageMessage'
has_many :images, -> { select("#{Image.table_name}.*, #{ImageMessage.table_name}.caption AS caption") }, :class_name => 'Image', :through => :image_messages, dependent: :destroy
2. ActiveRecord 关联扩展
这是 Rails 的一个鲜为人知的特性,它可以让你玩弄collection
对象。它的方式是扩展has_many
您创建的关系:
class AccountGroup < ActiveRecord::Base
has_many :accounts do
def X
#your code here
end
end
end
我们只有这种方法适用于集合,但你可以用它做各种事情。您应该查看本教程以了解更多信息
更新
我们刚刚通过使用扩展模块来完成这项工作:
#app/models/message.rb
Class Message < ActiveRecord::Base
has_many :image_messages #-> join model
has_many :images, through: :image_messages, extend: ImageCaption
end
#app/models/concerns/image_caption.rb
module ImageCaption
#Load
def load
captions.each do |caption|
proxy_association.target << caption
end
end
#Private
private
#Captions
def captions
return_array = []
through_collection.each_with_index do |through,i|
associate = through.send(reflection_name)
associate.assign_attributes({caption: items[i]})
return_array.concat Array.new(1).fill( associate )
end
return return_array
end
#######################
# Variables #
#######################
#Association
def reflection_name
proxy_association.source_reflection.name
end
#Foreign Key
def through_source_key
proxy_association.reflection.source_reflection.foreign_key
end
#Primary Key
def through_primary_key
proxy_association.reflection.through_reflection.active_record_primary_key
end
#Through Name
def through_name
proxy_association.reflection.through_reflection.name
end
#Through
def through_collection
proxy_association.owner.send through_name
end
#Captions
def items
through_collection.map(&:caption)
end
#Target
def target_collection
#load_target
proxy_association.target
end
end
对变量函数的这个要点的支持
这基本上覆盖了类中的load
ActiveRecord 函数CollectionProxy
,并使用它来创建我们自己的proxy_association.target
数组:)
如果您需要有关如何实施的任何信息,请在评论中询问