【问题标题】:Models -> has_many -> Twice模型 -> has_many -> 两次
【发布时间】:2011-09-01 03:18:54
【问题描述】:

所以我在这里有一个有点令人困惑的关系,即注释、组和用户之间的关系。最后我在我的模型中使用了 has_many 两次。但我目前专注于 Note 与 Group 的关系。

背景:一个组可以有一个注释。用户也可以有注释。这就是为什么我的笔记是多态的。但是,我还创建了一个名为 Tag 的连接模型,以便一个 Note 可以属于多个组。不过,在我的代码中,我最终得到了多个“has_many :notes”。请参阅下面的所有代码。做这样的事情的正确方法是什么?

提前致谢!

note.rb

belongs_to :notable, :polymorphic => true
has_many :tags
has_many :groups, :through => :tags

user.rb

has_many :notes, :as => :notable

group.rb

has_many :notes, :as => :notable
has_many :tags
has_many :notes, :through => :tags

tag.rb

belongs_to :note
belongs_to :group

【问题讨论】:

    标签: ruby-on-rails model associations has-many has-many-through


    【解决方案1】:

    你只需要给它一个不同的名字。

    class Group
      has_many :notes, :as => :notable
      has_many :tags
      has_many :tagged_notes, :class_name => 'Note', :through => :tags
    end
    

    如果您只想为 :as => :notable 部分添加一个注释(这在您的问题中不是很清楚),您可以这样做:

    class Group
      has_one :note, :as => :notable
      has_many :tags
      has_many :notes, :through => :tags
    end
    

    名称必须不同。尽管使用 notenotes 可能不太清楚代码其他部分的区别。

    【讨论】:

    • 嗯,一个组总是会有很多笔记,而不仅仅是一个。我想做的就是这个。某人可以写一个便条,然后选中一些框,确定他们想将便条应用到哪些组。所以一个组可以有很多笔记,一个笔记可以属于许多不同的组。这更有意义吗?
    • 感谢您的回答,我会考虑将其称为 tagged_note 我猜,不太熟悉。
    猜你喜欢
    • 2016-03-29
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多