【问题标题】:Rails model has_many :items twiceRails 模型 has_many :items 两次
【发布时间】:2016-03-29 04:33:22
【问题描述】:

用户.rb

class User < ActiveRecord::Base
   has_many :videos
end

video.rb

class Video < ActiveRecord::Base
    belongs_to :user
end

我希望用户能够将不belongs_to他们(不是他们上传)的视频添加到他们的“收藏”中。

我想我需要一个多对多的关系,所以我考虑了一个 has_many 通过“集合”连接模型。我不明白如何区分上传的视频和收集的视频。

我还考虑了两个新模型,即 belongs_to :userhas_many :videos 通过“collected_videos”连接模型的“收藏”模型。

有没有更好的方法来解决这个问题?抱歉,如果我的问题不清楚,对于 StackOverflow 和一般开发来说都是新手。谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model-view-controller database-design model


    【解决方案1】:

    如果我理解你的要求正确,我认为你可以设置这样的东西来实现你想要的:

    class User
      has_and_belongs_to_many :videos
    end
    
    class Video
      has_and_belongs_to_many :users
      belongs_to :owner, class_name: "User"
    end
    

    仔细查看has_and_belongs_to_many 的文档:http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

    【讨论】:

    • @tet5uo 上述答案是否解决了您的问题?注意到这个答案还没有被标记为接受:)
    猜你喜欢
    • 2011-09-01
    • 2016-12-23
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多