【问题标题】:User_id is not passed to secondary controllerUser_id 未传递给辅助控制器
【发布时间】:2017-09-10 19:11:45
【问题描述】:

我正在 Rails 中构建一个相当基本的应用程序,使用两个主要控制器,用户和 cmets。我正在使用 Bcrypt 并具有用于用户加密的 secure_password 和嵌套资源,以便用户 has_many cmets 和 cmets belongs_to 用户。

当我尝试保存新评论时,我收到以下错误消息:评论的未知属性'user_id'。似乎 user_id 没有传递给控制器​​,尽管这应该使用 cmets 控制器中定义的 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

当我尝试保存我登录的 cmets 时,我不确定为什么 user_id 不会传递给控制器​​。非常感谢您的建议,谢谢。

【问题讨论】:

    标签: ruby-on-rails bcrypt controllers


    【解决方案1】:

    当我尝试保存新评论时,我收到的错误消息是 以下:“评论的未知属性'user_id'。

    当使用belongs_to关联关联时,您必须实际将列添加到表中以存储外键。

    您可以使用以下命令生成迁移:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 2019-07-03
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2020-09-17
      相关资源
      最近更新 更多