【发布时间】:2018-03-30 15:43:19
【问题描述】:
我正在尝试制作一个类似 reddit 的网站,所以我创建了一个应该包含帖子的论坛模型,因此我还创建了一个帖子模型,我想成为论坛的孩子。我对这个想法的代码是:
论坛.rb
class Forum < ApplicationRecord
has_many :posts
validates :name, presence: true,
length: { minimum: 2 }
end
post.rb
class Post < ApplicationRecord
validates :title, presence: true,
length: { minimum: 5 }
validates :text, presence: true,
length: { minimum: 5 }
belongs_to :forum
end
对应的迁移是:
create_forums.rb
class CreateForums < ActiveRecord::Migration[5.1]
def change
create_table :forums do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
create_posts.rb
class CreatePosts < ActiveRecord::Migration[5.1]
def change
create_table :posts do |t|
t.string :title
t.text :text
t.references :forum, index: true, foreign_key: true
t.timestamps
end
end
end
当我尝试在某个论坛中创建新帖子时,我的问题出现了。例如,如果我运行@forum.posts.create(title: "Title", text: "Body"),我会得到ActiveModel::UnknownAttributeError in Posts#new,描述为unknown attribute 'forum_id' for Post。
发生了什么事?
【问题讨论】:
-
@forum 是一个有效的对象吗?
-
@hashrocket 是的
标签: ruby-on-rails ruby-on-rails-5