【问题标题】:Rails Associations - specific caseRails 协会 - 特定案例
【发布时间】:2017-08-27 10:41:30
【问题描述】:

我有一个帖子、图像和视频模型,我需要对帖子、图像和视频之间的关联进行建模。图片和视频媒体应该属于一个帖子。我还需要发布记录才能通过调用@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

感谢您的帮助:)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations


    【解决方案1】:

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

    界面不太一样,但似乎足够接近,可以作为一个选项进行调查。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多