質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

2回答

712閲覧

railsでNoMethodError in Money#fileがでる

hashimo1013

総合スコア6

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2020/01/23 16:42

画像ファイルを投稿しようとしたところ
NoMethodError in Money#file
Showing /Users/hasimo/Desktop/okane/app/views/money/_form.html.erb where line #2 raised:
undefined method `errors' for nil:NilClass
とでてしまいます。

動作としては、newビューで画像の選択し、投稿ボタンを押すとcreateアクションにいき、
画像が含まれているとfileアクションにいくようにしてます。
fileアクションではWEBapiを使い、画像解析を行ってレスポンスをfileビューで返す、という流れです。

money_controller.rb class MoneyController < ApplicationController before_action :set_money, only: [:show, :edit, :update, :destroy] def index @money = current_user.moneys this_month_expenses prevent_month_expenses end def show @money = Money.new end def new @money = Money.new end def edit end def create @money = Money.new(money_params) if @money.image.present? $moneyimage = @money redirect_to action: 'file' else respond_to do |format| if @money.save format.html { redirect_to @money, notice: 'Money was successfully created.' } format.json { render :show, status: :created, location: @money } else format.html { render :new } format.json { render json: @money.errors, status: :unprocessable_entity } end end end end def update respond_to do |format| if @money.update(money_params) format.html { redirect_to @money, notice: 'Money was successfully updated.' } format.json { render :show, status: :ok, location: @money } else format.html { render :edit } format.json { render json: @money.errors, status: :unprocessable_entity } end end end def destroy @money.destroy respond_to do |format| format.html { redirect_to money_index_url, notice: 'Money was successfully destroyed.' } format.json { head :no_content } end end private def file image_file = "public#{$moneyimage.image.url}" api_key = ENV['GOOGLE_VISION_API_KEY'] api_url = "https://vision.googleapis.com/v1/images:annotate?key=#{api_key}" base64_image = Base64.strict_encode64(File.new(image_file, 'rb').read) body = { requests: [{ image: { content: base64_image }, features: [ { type: 'DOCUMENT_TEXT_DETECTION', maxResults: 1 } ] }] }.to_json uri = URI.parse(api_url) https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request["Content-Type"] = "application/json" response = https.request(request, body) @response_rb = JSON.parse(response.body) @description = @response_rb["responses"][0]["textAnnotations"][0]["description"] str = @description.match(/合計\d*\D*(\d\D*\d*)/) num = str[1] num1 = num.gsub(/(\d{0,3}),(\d{3})/, '\1\2') @num = num1.to_i @money = Money.new @money.expenses = @num end def set_money @money = Money.find(params[:id]) end def money_params params.require(:money).permit(:expenses, :image).merge(user_id:current_user.id) end def total_expenses sum = 0 @money.each do |money| sum += money.expenses end return sum end def this_month_expenses @this_month_data = [] @this_month_sum = 0 this_month = Date.today.all_month # all_monthをDate.todayに適用すると、今月の年月日データを取得できる。 @money.each do |money| if (this_month.include?(Date.parse(money[:created_at].to_s))) # 今月の日にちの中にhoge[:created_at]の年月日が含まれていれば、trueを返す。 @this_month_data << money @this_month_sum += money.expenses end end end def prevent_month_expenses @prevent_month_data = [] @prevent_month_sum = 0 @prevent_month_data = @money.where(created_at: Time.now.prev_month.beginning_of_month..Time.now.prev_month.end_of_month) @prevent_month_data.each do |money| @prevent_month_sum += money.expenses end end end
new.html.erb <h1>New Money</h1> <%= render 'form', money: @money %> <%= link_to 'Back', money_index_path %>
file.html.erb <p id="notice"><%= notice %></p> <p> がぞーとーこー</p> <p> <%= image_tag $moneyimage.image.url %> </p> <%= @num %> <br> <%= @description %> <%= render 'form', money: @money %> <%= link_to 'Back', money_index_path %>
_form.html.erb <%= form_with(model: money, local: true) do |form| %> <% if money.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(money.errors.count, "error") %> prohibited this money from being saved:</h2> <ul> <% money.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class = "input"> <%= form.number_field :expenses %> <div class="actions"> <%= form.submit %> </div> <div class = "file"> <%= form.file_field :image %> </div> <% end %>
routes.rb Rails.application.routes.draw do root "money#index" devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :money do collection do get 'file' end end end

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

自己解決できたかも。
おそらくですが、fileアクションをプライベートメソッドにしてしまったため
アクションとして認識されてなかったようです。
よって、fileメソッド内でいくら定義しても、メソッドが呼ばれてないので実行そのものがされてないので
@moneyがnilだったようです。

プライベートを外すと動くようになりました。

投稿2020/01/24 04:25

hashimo1013

総合スコア6

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

勘違いしてました。書き直します

投稿2020/01/23 20:49

編集2020/01/23 20:58
winterboum

総合スコア23284

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問