LoginSignup
2
0

More than 3 years have passed since last update.

【Rails】ストロングパラメーターparam is missing or the value is empty:について

Last updated at Posted at 2021-04-18

今回問題となる箇所

def create
    customer = Customer.new(customer_params)
    if customer.save
       render json: { status: 'success11111', data: customer }
    else
      render json: { status: 'error', data: customer.errors }
    end
  end

 private
  def customer_params
    params.require(:customer).permit(:name, :age, :sex, :memo) 
  end

です。
どういった問題かといいますと

param is missing or the value is empty:

パラメーターがないか、値が空であるといった内容でした。
今回の場合はapiの実装中ということで、Postmanを利用し、リクエストに対するレスポンスの確認を行っていました。
Image from Gyazo
こんな感じです。

いろいろ調べてみた結果、

def create
    customer = Customer.new(customer_params)
    if customer.save
       render json: { status: 'success11111', data: customer }
    else
      render json: { status: 'error', data: customer.errors }
    end
  end

 private
  def customer_params
    params.permit(:name, :age, :sex, :memo) 
  end

require(:customer)を消せばエラー無くレスポンスがかえってきました。

原因はおそらく

controller側で@customer = Customer.newやなどの書き忘れが原因なことが多いようです!

<%= form_with model: Customer.new do %>
あるいはcontroller側で@customer = Customer.newとして
<%= form_with model: @customer do %

とした場合、パラメータは

<ActionController::Parameters {(略),"url"=>"https://(略)", "customer"=>{"group_id"=>"5", "commit"=>"Save ", "controller"=>"customer"}, "action"=>"create"} permitted: true>

となり、ストロングパラメータは正常に実行されるはずです
今回の場合はPostmanにてリクエストを送信していて、

<%= form_with model: @customer, url: customers_path, method: :post do %>

といったようにviewファイルからモデルを指定して送られたリクエストではないため、param is missing or the value is empty:が起きたと考えられます!

今回私はviewファイルを作成していない段階の事例でしたが、最初にも記述しましたがこのエラーに関しての多くは@customer = Custome.newなどの書き忘れが原因なことが多かったり、複数形のスペルミスだったりするようなので、チェックしてみてください!

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0