在“Beginning Rails 4”一书的第6章中遇到一些问题
表架构
ActiveRecord::Schema.define(version: 20160304183431) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "published_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "excerpt"
t.string "location"
t.integer "user_id"
end
create_table "articles_categories", id: false, force: :cascade do |t|
t.integer "article_id"
t.integer "category_id"
end
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "profiles", force: :cascade do |t|
t.integer "user_id"
t.string "name"
t.date "birthday"
t.text "bio"
t.string "color"
t.string "twitter"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "password"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
用这个播种了seed.rb文件:
user = User.create :email => 'mary@example.com', :password => 'guessit'
Category.create [{:name => 'Programming'},
{:name => 'Event'},
{:name => 'Travel'},
{:name => 'Music'},
{:name => 'TV'}]
然后进入控制台:
article = Article.last
#<Article id: 5, title: "Advanced Active Record", body: "Models need to relate to each other. In the real w...", published_at: "2016-03-03 00:00:00", created_at: "2016-03-04 06:35:27", updated_at: "2016-03-04 06:35:27", excerpt: nil, location: nil, user_id: nil>
category = Category.find_by_name('Programming')
#<Category id: 1, name: "Programming", created_at: "2016-03-04 18:40:57", updated_at: "2016-03-04 18:40:57">
article.categories << category
这是让我遇到麻烦的最后一行。每当我尝试article.categories << category
时,我都会每次收到此消息:NoMethodError: undefined method categories' for #<Article:0x007fdbc333a328>
为什么呢?
编辑
文章模型
class Article < ActiveRecord::Base
validates_presence_of :title, :body
belongs_to :user
has_and_belongs_to_many :categories
def long_title
"#{title} - #{published_at}"
end
end
类别模型
class Category < ActiveRecord::Base
has_and_belongs_to_many :articles
end
答案 0 :(得分:0)
除了这张表
create_table "articles_categories", force: :cascade do |t|
t.integer "article_id"
t.integer "category_id"
end
您还需要一个索引:
add_index "articles_categories", ["article_id", "category_id"], name: "index_articles_categories_on_article_id_and_category_id", unique: true, using: :btree
通过这种方式,rails的魔力将能够链接您的文章和类别。可能会有一些拼写错误,但你明白了。