首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails Associations -特定案例

Rails Associations -特定案例
EN

Stack Overflow用户
提问于 2017-08-27 18:41:30
回答 1查看 235关注 0票数 1

我有一个帖子,图像和视频模型,我需要模型之间的关联后,图像和视频。图像和视频媒体应属于帖子。我还需要post记录能够通过调用@post.post_media来获取所有相关的post_media。

我需要这些测试通过:

代码语言:javascript
复制
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

感谢您的帮助:)

EN

回答 1

Stack Overflow用户

发布于 2017-08-28 01:33:44

这看起来与单表继承非常接近,但并不完全相同,在单表继承中,您将VideoImage定义为PostMedia的子类型。

界面并不完全相同,但似乎足够接近,可以将其作为一种选择进行研究。

http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45904070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档