Имея некоторые проблемы в следующих гл 6 книги 'Начало Rails 4'NoMethodError в Rails консоли
Таблица схемы
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
ли населили seeds.rb файл с этим:
user = User.create :email => '[email protected]', :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>
Почему?
EDIT
Статья Модель
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
Как выглядят ваши модели статей и категорий? –
У вас есть ассоциации, определенные в моделях? То есть в классе Article has_and_belongs_to_many: категории? и has_and_belongs_to_many: статьи в категориях? – osman
@RickRunyon, просто добавил эту информацию. – user273072545345