LoginSignup
2
2

More than 3 years have passed since last update.

【個人アプリ開発メモ】ArgumentError (wrong number of arguments (given 0, expected 2)):の解決

Posted at

直面している問題

投稿しようとしたらできない。
なぜ?

ターミナルに以下のエラー文が表示された。

エラー文

ターミナル
ArgumentError (wrong number of arguments (given 0, expected 2)):
app/controllers/posts_controller.rb:21:in `create'

argumentとは引数のことらしい。
2つの引数がなければいけないのに、それが0になってるからダメだという。

引数が2つ必要?何のことだろう?

posts_controller.rb
def create
  @post = Post.new(post_params)  ここで止まってしまってる
  if @post.save
  redirect_back(fallback_location: root_path) # なぜredirect_to root_pathじゃダメなのかわかってない
else
  @posts = Post.includes(:user)
  flash.now[:alert] = '必須項目をしてください。' # フラッシュメッセージが出るか確認する
    redirect_back(fallback_location: root_path)
  end
end

private
  def post_params
    params.require(:post).permit(:food, :calorie, :protein, :fat, :carbo, :text, :image).merge(user_id: current_user.id)
  end

試してみたこと

binding.pryでpost_paramsの中身を確認してみよう。

[1] pry(#<PostsController>)> post_params
=> <ActionController::Parameters {"food"=>"うどん", "calorie"=>"10", "protein"=>"10", "fat"=>"10", "carbo"=>"10", "text"=>"うどんを食べました", "image"=>#<ActionDispatch::Http::UploadedFile:0x00007fc7e7b4eae0 @tempfile=#<Tempfile:/var/folders/sy/26p55v5j47s2zjd8h7vr8f6h0000gn/T/RackMultipart20200820-34304-1e1sjww.png>, @original_filename="image4.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"post[image]\"; filename=\"image4.png\"\r\nContent-Type: image/png\r\n">, "user_id"=>17} permitted: true>

ここが原因ではないようだ。

https://teratail.com/questions/164134
によれば、

ターミナル
ArgumentError (wrong number of arguments (given 0, expected 2)):

これは呼び出し側の引数の数 = 0
メソッド側の引数の数 = 2
という意味らしい。

呼び出し側の引数の数と、メソッド側と引数の数はそれぞれどこで設定してるのだろうか?

試したこと

画像を選択せずに、画像以外を投稿してみた。
その結果、これは問題なく投稿できた。
この結果からわかったのは、やはり問題は画像関連だということ。

画像を選択して、画像も投稿しようとするとエラーが生じる。
画像を投稿しようとすると、メソッド側の引数が2になる?

解決した。原因は「え?そこ?」という感じ

image_uploader.rb
#[300, 200][100, 100]という感じで2つあるとダメ
process resize_to_fit: [300, 200][100, 100]

#1つに戻したら解決した
process resize_to_fit: [300, 200]

前に投稿画像サイズの設定で、2通りのサイズを設定したいと思って上記のように設定していたが、これが邪魔だったみたい。
https://qiita.com/naota7118/items/33943b8887a4990645a9

余計なことしなければよかった。

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