我想创建从Post到User模型的关系。所以我创建了:
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
通过rake db:migration进行迁移。
当我添加新帖子时,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 [:post])?我觉得一切都很好......
答案 0 :(得分:0)
attr_accessible :text, :title, :image, :user_id
或者,而不是attr_accessible,只需这样做:
attr_protected