コンソールやpry-railsの有用性
エラーが起きたときは"binding.pry"もしくは"rails c"で調べるとわかりやすい
current_userのidやparamsのitem_id、Itemモデルの値段を調べていた時のコンソールやbinding.pryの一部のコピー
rails c
1] pry(main)> p current_user.id
NameError: undefined local variable or method `current_user' for main:Object
from (pry):1:in `__pry__'
[2] pry(main)> p @item.user.id
NoMethodError: undefined method `user' for nil:NilClass
Did you mean? super
from (pry):2:in `__pry__'
[3] pry(main)> Item.find(current_user.id)
NameError: undefined local variable or method `current_user' for main:Object
from (pry):3:in `__pry__'
→結局current_userは定義されてないのでparamsの中の値が使えるbinding.pryを試す
binding.pry
11: def create
=> 12: binding.pry
13: @user_info = UserInfo.new(user_info_params)
14: if @user_info.valid?
15: pay_item
16: @user_info.save
17: redirect_to item_path(@item)
18: else
19: render action: :index
20: end
21: end
[1] pry(#<PurchasesController>)> @item = Item.find(params[:item_id])
CACHE Item Load (0.0ms) SELECT `items`.* FROM `items` WHERE `items`.`id` = 4 LIMIT 1 [["id", 4], ["LIMIT", 1]]
↳ (pry):1:in `create'
=> #<Item:0x00007fd3e171fdb0
id: 4,
item_name: "あ",
item_text: "あ",
category_id: 3,
condition_id: 2,
shipping_id: 2,
sender_id: 3,
delivery_date_id: 2,
price: 2222222,
user_id: 1,
created_at: Sun, 13 Dec 2020 12:07:44 UTC +00:00,
updated_at: Sun, 13 Dec 2020 12:07:44 UTC +00:00>
[2] pry(#<PurchasesController>)> current_user
=> #<User id: 2, email: "s@s.s", nickname: "SSS", last_name: "ササ", first_name: "ササ", last_name_kana: "ササ", first_name_kana: "ササ", birth_date: "1932-03-03", created_at: "2020-12-10 16:39:19", updated_at: "2020-12-10 16:39:19">
[3] pry(#<PurchasesController>)> current_user.id
=> 2
[4] pry(#<PurchasesController>)> current_user[:id]
=> 2
[5] pry(#<PurchasesController>)> @item.id
=> 4
[6] pry(#<PurchasesController>)> @item[:user_id]
=> 1
[7] pry(#<PurchasesController>)> item_id
NameError: undefined local variable or method `item_id' for #<PurchasesController:0x00007fd3c322d190>
Did you mean? item_url
from (pry):7:in `create'
[8] pry(#<PurchasesController>)> :item_id
=> :item_id
[11] pry(#<PurchasesController>)> params
=> <ActionController::Parameters {"authenticity_token"=>"xc85a50Pk8j+cWdEUV28OzggqHNQFvEVCTcEYMTJYzK5UihjtmL1H5g5pfrtX+mNj9yDJNm36/cYbMMp858vRw==", "user_info"=>{"postal_code"=>"", "prefecture_id"=>"1", "city"=>"", "address_line"=>"", "building"=>"", "tel"=>""}, "controller"=>"purchases", "action"=>"create", "item_id"=>"4"} permitted: false>
[12] pry(#<PurchasesController>)> params[:item_id]
=> "4"
[13] pry(#<PurchasesController>)> Item.find(params[:item_id])[:price]
CACHE Item Load (0.1ms) SELECT `items`.* FROM `items` WHERE `items`.`id` = 4 LIMIT 1 [["id", 4], ["LIMIT", 1]]
↳ (pry):13:in `create'
=> 2222222
上記黄色と赤の部分の値が欲しいがために色々と試した(実際はもっといろいろ試しているが…)
今思うと当然当たり前のことがわかっていない。
@item = Item.find(params[:item_id])
を定義している以上、@item[:price] で値段は出てくる。
(というかそもそも@item.priceでいい)
VS上で試すとブラウザをリロードしなければならず、特にフォーム関連はいちいちフォームに入力したりするのが手間なので、今後はこっちで調べながら行こうと思う。