User_id 未传递给辅助控制器
User_id is not passed to secondary controller
我正在 Rails 中构建一个相当基本的应用程序,使用两个主要控制器、用户和评论。我正在使用 Bcrypt 并具有 secure_password 用于用户加密和嵌套资源,以便用户 has_many 评论和评论 belongs_to 用户。
当我尝试保存新评论时,收到的错误消息如下:评论的属性 'user_id' 未知。似乎 user_id 没有传递给控制器,尽管这应该使用评论控制器中定义的 current_user 来完成 - 目前看起来像这样:
def new
@user = current_user
@comment = Comment.new
@comment.save
end
def create
@user = current_user
@comment = @user.comments.new(comment_params)
@comment.save
redirect_to user_comments_path, notice: "Thank you for your comment!"
end
......
private
def comment_params
params.require(:comment).permit(:user_id, :location, :title, :body)
end
当我尝试保存评论时我已登录,所以我不确定为什么 user_id 不会传递给控制器。非常感谢您的建议,谢谢。
When I try to save a new comment, the error message I receive is the
following: "unknown attribute 'user_id' for Comment.
使用 belongs_to
关联时,您必须实际向 table 添加列以存储外键。
您可以通过以下方式生成迁移:
rails g migration add_user_id_to_comments user:belongs_to
然后使用 rails db:migrate
迁移。
您的控制器也有很多问题:
def new
@comment = current_user.comments.new
# never save in new method!
end
def create
@comment = current_user.comments.new(comment_params)
# you always have to check if save/update was successful
if comment.save
redirect_to user_comments_path, notice: "Thank you for your comment!"
else
render :new
end
end
无需将 current_user
保存到单独的实例变量,因为您应该将其记忆。
def current_user
@current_user ||= session[:user_id] ? User.find(session[:user_id]) : nil
end
我正在 Rails 中构建一个相当基本的应用程序,使用两个主要控制器、用户和评论。我正在使用 Bcrypt 并具有 secure_password 用于用户加密和嵌套资源,以便用户 has_many 评论和评论 belongs_to 用户。
当我尝试保存新评论时,收到的错误消息如下:评论的属性 'user_id' 未知。似乎 user_id 没有传递给控制器,尽管这应该使用评论控制器中定义的 current_user 来完成 - 目前看起来像这样:
def new
@user = current_user
@comment = Comment.new
@comment.save
end
def create
@user = current_user
@comment = @user.comments.new(comment_params)
@comment.save
redirect_to user_comments_path, notice: "Thank you for your comment!"
end
......
private
def comment_params
params.require(:comment).permit(:user_id, :location, :title, :body)
end
当我尝试保存评论时我已登录,所以我不确定为什么 user_id 不会传递给控制器。非常感谢您的建议,谢谢。
When I try to save a new comment, the error message I receive is the following: "unknown attribute 'user_id' for Comment.
使用 belongs_to
关联时,您必须实际向 table 添加列以存储外键。
您可以通过以下方式生成迁移:
rails g migration add_user_id_to_comments user:belongs_to
然后使用 rails db:migrate
迁移。
您的控制器也有很多问题:
def new
@comment = current_user.comments.new
# never save in new method!
end
def create
@comment = current_user.comments.new(comment_params)
# you always have to check if save/update was successful
if comment.save
redirect_to user_comments_path, notice: "Thank you for your comment!"
else
render :new
end
end
无需将 current_user
保存到单独的实例变量,因为您应该将其记忆。
def current_user
@current_user ||= session[:user_id] ? User.find(session[:user_id]) : nil
end