模型是 a User
,其中有许多Contact
s。Post
s 和Image
s 可以 Contact
通过 a 发布到 s ContactPublishment
。
User
具有允许轻松访问s 和visible_posts
s发布到的方法。visible_images
Post
Image
问题是,虽然user.visible_images
工作user.visible_posts
完美,但依赖这些关系的规范变得疯狂:
如果删除规范的测试visible_images
或visible_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