我想创建从发布到用户模型的关系。所以我创建:sqllite数据库中的关系没有外键添加
class Post < ActiveRecord::Base
attr_accessible :text, :title, :image, :user_id
has_many :comments
belongs_to :user
mount_uploader :image, ImageUploader
end
和User.rb:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :posts
end
然后我将文件添加到数据库迁移:
class AddUserIdToPost < ActiveRecord::Migration
def change
add_column :posts, :user_id, :integer
end
end
并提出通过耙分贝迁移:迁移。
当我添加新帖子时,user_id(在dataBase中)的值为空,但列存在。 Post_Controller的
部分:
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
我应该怎么做@post = Post.new(PARAMS [:帖])?我认为一切都很好...
您可能需要做':user_id''attr_accessible'在'POST'类 – 2013-04-04 16:48:17
我加:user_id但没有任何改变。我检查数据库,并且我仍然在user_id上有空值(表格帖子) – Sawior91 2013-04-04 16:57:46
你在哪里给'user_id'一个值?它在'params [:post]'里面吗? – 2013-04-04 17:04:23