0

has_many :through为我正在创建的 Rails 应用程序创建了一个关系。但是,我无法为多对多关系提供嵌套属性。

我的模型如下:

文章.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

标签.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

这个问题就解决了。

对于任何需要知道的人:

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

感谢丹·里迪的帮助!

4

2 回答 2

2

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

class ArticleTag < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end
于 2013-05-09T02:52:03.637 回答
1

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

于 2013-08-19T20:42:07.917 回答