【问题标题】:Rails (param is missing or the value is empty)Rails(参数丢失或值为空)
【发布时间】:2015-05-29 13:26:12
【问题描述】:

我正在使用 rails 4,并且我读到 attr_accessible 最好不要在此版本中使用。我已经创建了该代码:

class UsersController < ApplicationController
  def new
    @user = User.new(user_params)
  end

  private
  ## Strong Parameters 
  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end

但它给了我这个错误:

ActionController::ParameterMissing in UsersController#new
param is missing or the value is empty: user

我正在尝试显示该 html.erb:

<%= form_for :user do |f| %>
    <%= f.text_field :name %>
    <%= f.text_field :email %>
    <%= f.text_field :password %>
    <%= f.text_field :password_confirmation %>
    <%= f.label :submit %>
<% end %>

有什么解决办法吗?

【问题讨论】:

  • 通常new 操作将是@user = User.new,因为没有user_params 从视图中回复。
  • 在这种情况下,它会给出一个错误,即密码是未定义的方法
  • 取得进展...让我们解决您对attr_accessor 的评论。不确定你在哪里读到的,但我认为你需要定义任何没有以这种方式保留在模型中的属性。你能用你的模型代码更新你的帖子吗?
  • 好吧,将这个attr_accessor :name, :email, :password, :password_confirmation 添加到模型中,但现在我收到错误Couldn't find User with 'id'=create(在显示功能中)
  • 将它们添加到您的问题 John,而不是 cmets。

标签: ruby-on-rails ruby ruby-on-rails-4 parameters


【解决方案1】:

通常,新操作是 @user = User.new,因为没有 user_params 从视图中回复。

【讨论】:

    【解决方案2】:
    class UsersController < ApplicationController
      def new
        @user = User.new
      end
    
      def create
        @user = User.new(user_params)
        if @user.save
          redirect_to user_path(@user)
        else
          render :action => 'new'
        end
      end 
    
      private
      def user_params
        params.require(:user).permit(:name, :email, :password, :password_confirmation)
      end
    end
    

    基本上在实例化对象时,您不需要调用 user_params 。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多