Rails'DB - 对于has_many通过关系没有这样的列'错误

时间:2013-05-09 02:08:44

标签: ruby-on-rails ruby many-to-many nested-attributes

我为正在创建的rails应用创建了has_many :through关系。但是,我无法拥有多对多关系的嵌套属性。

我的模型如下:

article.rb

class Article < ActiveRecord::Base
  attr_accessible :body, :title
  has_many :article_tags
  has_many :tags, :through => :article_tags, :foreign_key => :tag_id    
  accepts_nested_attributes_for :tags, reject_if: :all_blank    
  attr_accessible :tags_attributes    
  validates_presence_of [:body, :title]
end

tag.rb:

class Tag < ActiveRecord::Base
   has_many :article_tags
   has_many :articles, :through => :article_tags, :foreign_key => :article_id
   attr_accessible :name
   validates_presence_of :name

   accepts_nested_attributes_for :articles, reject_if: :all_blank

   attr_accessible :articles_attributes
end

article_tag.rb:

class ArticleTag < ActiveRecord::Base
 belongs_to :article
 belongs_to :tag
end

现在在我的文章(show.html.slim)的视图中,我想使用该行显示属于该文章的所有标记:

- @article.tags.each do |t|
  = t.name

然而,我收到错误: SQLite3::SQLException: no such column: article_tags.article_id: SELECT "tags".* FROM "tags" INNER JOIN "article_tags" ON "tags"."id" = "article_tags"."tag_id" WHERE "article_tags"."article_id" = 1

这个问题已经解决了。

对于任何需要知道的人:

您必须手动在迁移和架构中添加外键。我加了他们瞧!它有效!

感谢Dan Reedy的帮助!

2 个答案:

答案 0 :(得分:2)

您的ArticleTag课程不正确。 belongs_to关联应该是单数的。

class ArticleTag < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end

答案 1 :(得分:1)

在这种情况下,您必须使用has_and_belongs_to_many