0
我正在使用rails 4.2.0。和我收到此错误:模型错误中的滑轨关联
ActiveRecord::HasManyThroughAssociationNotFoundError:
Could not find the association :taggings in model Article
这里是我的模型:
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, :through => :taggings
end
class Article < ActiveRecord::Base
has_many :comments
has_many :taggings
has_many :tags, :through => :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :article
end
标记是条和标签之间的许多一对多关系的中介模式。
如果有帮助,我的架构:
ActiveRecord::Schema.define(version: 20150224161732) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "comments", force: :cascade do |t|
t.string "author_name"
t.text "body"
t.integer "article_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "comments", ["article_id"], name: "index_comments_on_article_id"
create_table "taggings", force: :cascade do |t|
t.integer "tag_id"
t.integer "article_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "taggings", ["article_id"], name: "index_taggings_on_article_id"
add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id"
create_table "tags", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
我在铁轨控制台运行这段代码来测试我的协会:
a = Article.first
a.tags.create name: "cool"
我得到上述错误。
我已经看到类似的问题,如果您的答案是“如果您已经通过了::x,您必须首先有has_many:x”,但我不认为这是我的问题。
也许复制和粘贴失败,但是这是一个语法错误:'has_many:tags,:through:taggings'。它可以是':through =>:taggings'或'through::taggings'。 – Robin 2015-02-24 17:38:57
没有运气,对不起:)。虽然你的建议将有助于未来的项目!我喜欢使用这种火箭。 – itiswicked 2015-02-24 17:47:25
出于好奇,这项工作: 'a = Article.first' 'a.tags << Tag.new(name:“cool”)' – tagCincy 2015-02-24 18:47:43