LoginSignup
0
0

More than 3 years have passed since last update.

[Rails] user_idのwrong number of arguments (given 2, expected 0..1)の解消法

Posted at

前提

deviseを導入してユーザーと投稿を紐づけるところ
(deviseなくてもいいがcurrent_userは@current_userで定義する必要あり)

やったこと

こちらを参考に**を追加

@gear = Gear.new(
  **gear_params,
  user_id: current_user.id
)

hash key "" is not a Symbolという謎のエラーにより撃沈

gear_paramsメソッドを使わずに全部書いてみた

@gear = Gear.new(
      category: params[:category],
      name: params[:name],
      maker: params[:maker],
      price: params[:price],
      memo: params[:memo],
      user_id: current_user.id
      )

なぜかrollbackされデータベースに保存されず。。
ActiveRecord::RecordInvalid (バリデーションに失敗しました: Userを入力してください
(未解決)

解決方法

完全に分けて書けばハッシュをシンボルにとか考えずに済む

def create
    @gear = Gear.new(
      gear_params
      )
    @gear.user_id = current_user.id
      .
      .
      .
end

参考にさせていただいたサイト

ユーザと紐付けしたモデルから投稿を保存するのに躓いたので。備忘録として

補足

gear_paramsはこう書いています

  private
  def gear_params
    params.require(:gear).permit(:category, :name, :maker, :price, :memo)
  end
0
0
0

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
0
0