Ruby on rails ActiveRecord覆盖有很多关系
因此,我试图覆盖rails 4.2应用程序中的一个关系Ruby on rails ActiveRecord覆盖有很多关系,ruby-on-rails,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,因此,我试图覆盖rails 4.2应用程序中的一个关系has\u many 我有一个模型事件谁有很多:图片 事件也可以有一个:联系人,而这个联系人也可以有许多:图片 我试图实现的是,当我们调用event.picturables时,is返回事件的picturables,以及联系人的属性 我试着用“扩展关联”来做这件事: has_many :picturables, ->{ order(:position) }, as: :picturable, class_name: "Picturable
has\u many
我有一个模型事件
谁有很多:图片
事件
也可以有一个:联系人
,而这个联系人
也可以有许多:图片
我试图实现的是,当我们调用event.picturables
时,is返回事件的picturables
,以及联系人的属性
我试着用“扩展关联”来做这件事:
has_many :picturables, ->{ order(:position) }, as: :picturable, class_name: "Picturable", dependent: :delete_all do
def <missing_name>
event = proxy_association.owner
event.contact.present? ? event.picturables + event.contact.picturables : event.picturables
end
def poney
event = proxy_association.owner
event.contact.present? ? event.picturables + event.contact.picturables : event.picturables
end
end
手工创建“where”的优点是,我们仍然有一个ActiveRecord:RelationProxy作为返回,因为当我创建event.picturables+event.contact.picturables时,它返回一个数组您能否澄清“我试图命名方法self
或本身
但它不起作用”的意思?你说的是
方法吗?我想你可以简单地在事件
类中重写def self.picturables
,使用你已经在使用的逻辑?…你猜对了,我尝试用self或self替换,但它不起作用。我试图覆盖事件类中的图片,当我们调用event.picturables时,这是可行的,但是当我们调用event.pictures时,我们没有联系人的图片(Picturable是一个用于多对多关系的表)您能澄清一下您的意思吗“我试图将方法命名为self
或本身
,但它不起作用"? 你说的是
方法吗?我想你可以简单地在事件
类中重写def self.picturables
,使用你已经在使用的逻辑?…你猜对了,我尝试用self或self替换,但它不起作用。我试图覆盖事件类中的可图片,当我们调用event.picturables时,这是可行的,但是当我们调用event.pictures时,我们没有联系人的图片(Picturable是用于多对多关系的表)
def picturables
unless contact.nil?
Picturable.where('(picturable_id = ? AND picturable_type = ?) OR (picturable_id = ? AND picturable_type = ?)', id, 'Event', contact.id, 'Contact')
else
super
end
end
def pictures
Picture.where(id: picturables.map(&:picture_id))
end