多个has_many through到同一多态性表,但由于不同的源类,在测试中失败,但实际上起作用



模型是User,它具有许多Contact s。Post S和Image S可以通过ContactPublishment发布到ContactS。

User具有visible_postsvisible_images的方法,可以轻松访问Post S和Image s发布的方法。

问题是,虽然user.visible_imagesuser.visible_posts工作完美地工作,但依赖这些关系的规格正在疯狂:

如果从规格中删除visible_images的测试或visible_posts的测试,则剩余的测试通过。如果我两者都离开,第二个失败。我可以切换测试的顺序,但仍然是第二次失败。怪异?

这是代码样本,使用导轨3.2.15:

class User < ActiveRecord::Base
  ...
  has_many :visible_posts, through: :contact_publishments, source: :publishable, source_type: 'Post'
  has_many :visible_images, through: :contact_publishments, source: :publishable, source_type: 'Image'
end
class Contact < ActiveRecord::Base
  ...
  belongs_to :represented_user, class_name: User.name
  has_many :contact_publishments
end
class ContactPublishment < ActiveRecord::Base
  ...
  belongs_to :contact
  belongs_to :publishable, polymorphic: true
end
class Post < ActiveRecord::Base
  ...
  has_many :contact_publishments, as: :publishable, dependent: :destroy
  has_many :contacts, through: :contact_publishments
end
class Image < ActiveRecord::Base
  ...
  has_many :contact_publishments, as: :publishable, dependent: :destroy
  has_many :contacts, through: :contact_publishments
end

describe User do
  ...
  it "#visible_images" do
    user = create :user
    image = create :image
    image.contacts << create(:contact, represented_user: user)
    user.visible_images.should == [image]
  end
  it "#visible_posts" do
    user = create :user
    post = create :post
    post.contacts << create(:contact, represented_user: user)
    user.visible_posts.should == [post]
  end
end

,所以我最终解决了它,但不是我想要的方式。我刚刚写了一份手册加入查询。有趣的是,这触发了与我的原始解决方案触发相同的精确SQL查询,但只有以某种方式使用该解决方案。铁轨中的错误?

class User < ActiveRecord::Base
  ...
  [Post, Image].each do |publishable|
    define_method("visible_#{publishable.name.pluralize.underscore}") do
      publishable.joins(:users).where('users.id' => self.id)
    end
  end
end

相关内容

  • 没有找到相关文章

最新更新