Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails ActiveRecord覆盖有很多关系_Ruby On Rails_Ruby On Rails 4_Activerecord - Fatal编程技术网

Ruby on rails ActiveRecord覆盖有很多关系

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

因此,我试图覆盖rails 4.2应用程序中的一个关系
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