0

模型是 a User,其中有许多Contacts。Posts 和Images 可以 Contact通过 a 发布到 s ContactPublishment

User具有允许轻松访问s 和visible_postss发布到的方法。visible_imagesPostImage

问题是,虽然user.visible_images工作user.visible_posts完美,但依赖这些关系的规范变得疯狂:

如果删除规范的测试visible_imagesvisible_posts从规范中删除测试,则剩余的测试通过。如果我两个都离开,第二个失败。我可以切换测试的顺序,但第二个仍然失败。奇怪吧?

这是使用 Rails 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
4

1 回答 1

0

所以我最终解决了它,但不是以我想要的方式。我刚刚写了一个手动连接查询。有趣的是,这触发了与我的原始解决方案触发的完全相同的 SQL 查询,但不知何故,只有这个通过了规范。Rails 中的错误?

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
于 2014-01-31T19:52:47.360 回答