简体   繁体   English

Rails搜索=>模型关系

[英]Rails searching through => model relationship

I have a main model called 'Notes' which has the following: 我有一个名为“ Notes”的主要模型,该模型具有以下内容:

attr_accessible :name, :label_tokens
has_many :labelships
has_many :labels, :through => :labelships
attr_reader :label_tokens

So basically the Note_id & Label_id are kept in the Labelships table. 因此,基本上Note_id和Label_id保留在Labelships表中。

What i would like to do is create a list of distinct Labels and create a link on each value to the respective Note. 我想做的是创建一个不同标签的列表,并在每个值上创建指向相应注释的链接。

Example: Note 'mynote' has a label of 'git' associated through the labelship table, i would like Git to appear on a list of other labels, and then when i click on git, i get a list of Notes that have the label 'git' on them. 示例:注意'mynote'具有通过labelship表关联的'git'标签,我希望Git出现在其他标签列表中,然后当我单击git时,我会得到带有标签的Notes列表在他们上'git'。

Assuming you have the following models: 假设您具有以下模型:

class Note
  has_many :labelships
  has_many :labels, :through => :labelships
end

class Labelships
  belongs_to :note
  belongs_to :label
end

class Label
  has_many :labelships
  has_many :notes, :through => :labelships
end

Now given a label, you can get its notes as follows: 现在给了一个标签,您可以按以下方式获取其注释:

label.notes

To exclude the note in hand: 排除手头的笔记:

label.notes.where("id != ?", note.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM