ard*_*vis 4 model ruby-on-rails associations has-many has-many-through
所以我在这里有一个有点混乱的关系,在Note,Group和User之间.我最终在模型中使用了has_many两次.但我目前专注于Note&Group关系.
背景:一个小组可以有一个注释.用户也可以有笔记.这就是我的Note是多态的原因.但是,我还创建了一个名为Tag的连接模型,因此Note可以属于多个组.在我的代码中,我最终得到了多个'has_many:notes'.请参阅下面的所有代码.做这样的事情的正确方法是什么?
提前致谢!
belongs_to :notable, :polymorphic => true
has_many :tags
has_many :groups, :through => :tags
Run Code Online (Sandbox Code Playgroud)
has_many :notes, :as => :notable
Run Code Online (Sandbox Code Playgroud)
has_many :notes, :as => :notable
has_many :tags
has_many :notes, :through => :tags
Run Code Online (Sandbox Code Playgroud)
belongs_to :note
belongs_to :group
Run Code Online (Sandbox Code Playgroud)
你只需要给它一个不同的名字.
class Group
has_many :notes, :as => :notable
has_many :tags
has_many :tagged_notes, :class_name => 'Note', :through => :tags
end
Run Code Online (Sandbox Code Playgroud)
如果你只想要一个单独的音符:as => :notable(在你的问题中这不是很清楚),你可以这样做:
class Group
has_one :note, :as => :notable
has_many :tags
has_many :notes, :through => :tags
end
Run Code Online (Sandbox Code Playgroud)
名称必须不同.尽管与代码note相比notes,代码的其他部分可能并不十分清楚.