我想創建從發佈到用戶模型的關係。所以我創建: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