我有一个帖子,图像和视频模型,我需要模型之间的关联后,图像和视频。图像和视频媒体应属于帖子。我还需要post记录能够通过调用@post.post_media来获取所有相关的post_media。
我需要这些测试通过:
context "viedos" do
let(:post) { create(:post) }
let(:video) { create(:video) }
it "can associate and video" do
post.videos << video
expect(post.videos.last).to eql(video)
end
it "can create an associated video" do
video_attributes = attributes_for(:video)
post.videos.create(video_attributes)
expect(post.videos.last.attributes).to include(video_attributes.stringify_keys)
end
it "can create associated video as post_media" do
post.post_media.create(medium: video)
expect(post.videos.last).to eql(video)
end
end
context "post_media" do
let(:post) { create(:post) }
let(:video) { create(:video) }
let(:image) { create(:image) }
before do
post.videos << video
post.images << image
end
it "should return all post related media" do
expect(post.post_media.count).to eql(2)
expect(post.post_media.map(&:medium)).to match_array([video, image])
end
end感谢您的帮助:)
发布于 2017-08-28 01:33:44
这看起来与单表继承非常接近,但并不完全相同,在单表继承中,您将Video和Image定义为PostMedia的子类型。
界面并不完全相同,但似乎足够接近,可以将其作为一种选择进行研究。
http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html
https://stackoverflow.com/questions/45904070
复制相似问题