Rails HABTM协会

时间:2012-07-14 17:02:25

标签: ruby-on-rails associations has-and-belongs-to-many self-reference squeel

我有自我参考habtm分配。

class Label < AR::B
   has_and_belongs_to_many :a_label, :class_name => "Label",
            :join_table => "a_labels",
            :foreign_key => "label_id",
            :association_foreign_key => "a_label_id",
            :uniq => true
end

但是当我创建查询(使用squeel)时:

Label.select{:title}.where do
        id.in(Label.select{:a_label_id}.joins(:a_labels).where{
            labels.title.in(list)
          })

架构:

 labels:
 id | title | description | created_at

 a_labels
 label_id | a_label_id    

我收到了错误:

ActiveRecord::ConfigurationError:
   Association named 'a_labels' was not found; perhaps you misspelled it? 

我错的地方? 感谢。

1 个答案:

答案 0 :(得分:1)

看起来您只需要在关联名称中添加“s”即可。而不是“a_label”,改为“a_labels”。

class Label < AR::B
  has_and_belongs_to_many :a_labels, ...
    ...
end