Closed pekorinko closed 3 years ago
place_data_scraper.rbのsave_place
メソッドを以下に書き換え
@result = @scrape_process.fetch_place
の内容としてはselenium_tool.rb
のfetch_place
メソッドの返り値であり、具体的内容としてはhash = { place_name: facility_name, address: address, star_ave: star_ave }
が返ってくる 初めて検索される施設の場合は新たにPlaceのレコードを作成する
def save_place
uri = URI.parse(@url)
@lrd = uri.fragment.split('=')[1].split(',')[0]
place = Place.find_by(lrd: @lrd)
@result = @scrape_process.fetch_place
if place.present?
return(
place.update(
place_name: @result[:place_name],
address: @result[:address],
star_ave: @result[:star_ave],
)
)
end
create_place
end
def create_place Place.create( lrd: @lrd, place_name: @result[:place_name], address: @result[:address], star_ave: @result[:star_ave], ) end
## 上記を試した結果のエラー(既に検索したことがある施設で実施した)
- エラー内容:results_controller.rbの46行目`place_id = place.id`は定義されていないと怒られている
- 恐らくこのエラーが出ている原因は`place_data_scraper.rb`の`save_palce`メソッドの以下コードが原因(`place.present?`がtrue=Placeが既に存在する)際は`place_name`,`address`,`star_ave`を更新する)
- 上記箇所を原因として考えた理由としてはエラーメッセージで`NoMethodError (undefined method `id' for true:TrueClass):`となっている
【エラーの原因となっていると思しき箇所】→place_data_scraper.rbの
save_palce`
if place.present?
return(
place.update(
place_name: @result[:place_name],
address: @result[:address],
star_ave: @result[:star_ave],
)
)
end
【エラーの内容】 NoMethodError (undefined method `id' for true:TrueClass):
app/controllers/results_controller.rb:46:in `create'
![image](https://user-images.githubusercontent.com/61894818/118734760-fff91680-b879-11eb-9368-f8d8bbaa6e5b.png)
## 既に存在する施設の場合はレコードを上書きするコードを書く際に参考にした記事
- Railsドキュメント データベースを更新 https://railsdoc.com/page/model_update
## 新たに検索する施設に関しては上記のようにコードを書き換えたとしても問題なく動く
![image](https://user-images.githubusercontent.com/61894818/118735815-2f108780-b87c-11eb-924c-84df7d416a5c.png)
rails c
でやればちゃんと上書きされていること確認済み
【レコードを作る】
【既にあるlrd
のplace_name, address, star_aveを書き換えた】
place.update(place_name:"米屋",address:"藤沢",star_ave:2.0)
results_controller.rb
のcreateメソッドの以下部分においてplaceをputsした結果true
が返ってきたtrue
が返ってきてしまっているのが本エラーの原因
【`results_controller.rb`のcreateメソッド】
place = place_data_scraper.save_place
puts "#{place}======================="
place_id = place.id
【本来であればPlaceのレコードが返ってくるはずなのに`true`が返ってきている】
true=======================
既に存在する施設の場合はPlaceのレコードをアップデート、そのアップデートしたPlaceのレコードを戻り値とするようにした
【place_data_scraper.rb save_place
メソッド 改善前】
if place.present?
return(
place.update(
place_name: @result[:place_name],
address: @result[:address],
star_ave: @result[:star_ave],
)
)
end
【place_data_scraper.rb save_place
メソッド 改善後】
if place.present?
place.update(
place_name: @result[:place_name],
address: @result[:address],
star_ave: @result[:star_ave],
)
return place
end
現状とこれからやること(その理由)