【问题标题】:conception issue with a has_many associationhas_many 关联的概念问题
【发布时间】:2012-10-30 19:16:57
【问题描述】:

我的关联有问题。
我希望许多 VideoPost 可以引用相同的 VideoInformation。 然后我认为外键应该在 VideoPost 中,所以我从下面可以看到的 2 个模型开始。 但我无法访问@video_post.video_information(这似乎是有道理的,因为在 VideoPost 中没有关联)
我应该怎么做 ?我有点困惑

感谢您的帮助!

我的 VideoPost 模型:

# Table name: video_posts
#
#  id                   :integer          not null, primary key
#  user_id              :integer
#  video_information_id :integer
#  created_at           :datetime         not null
#  updated_at           :datetime         not null
class VideoPost < ActiveRecord::Base
  belongs_to :user

  attr_accessible :video_information_id
end

我的 VideoInformation 模型:

# Table name: video_informations
#
#  id              :integer          not null, primary key
#  title           :string(255)
#  description     :text
#  keywords        :text
#  duration        :integer
#  video_url       :string(255)
#  thumbnail_small :string(255)
#  thumbnail_large :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
class VideoInformation < ActiveRecord::Base
  has_many :video_posts
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations has-many


    【解决方案1】:

    你应该添加

    belongs_to :video_information
    

    进入 video_post.rb,因为当您定义关联时,您应该在两个模型中都这样做。

    here is some info你可能想看看

    【讨论】:

    • 是的,我想到了,但“VideoPost 属于 VideoInformation”的意思对我来说并不正确”(关于上下文)。你知道我的意思吗?
    • @Pontek 是的,如果你解释它而不注意你的用例。在不了解您的用例的情况下很难假设任何事情,但您可能可以将 VideoInformation 重命名为 Video,我可以监督您将从 Post 继承 VideoPost 以共享行为。
    猜你喜欢
    • 2011-02-28
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多