Railsでjbuilderを使ってjsonを返したいのですが...
railsで簡単な文書管理アプリのようなものを作っています。
コントローラー側からjson形式でviewに返す機能を実装中に以下のようなエラー発生しました。
発生している問題・エラーメッセージ
エラー箇所
jbuilder内の@変数(インスタンス変数)にメソッドがないと言われる(id以外も同様)
(/api/top/3.json にアクセス時)
undefined method `id' for nil:NilClass
該当のソースコード
(views/api/json/top.json.jbuilder内) json.sentence_id @sentences.id json.user_id @sentences.user_id json.source_id @sentences.source_id json.sentence @sentences.sentence 以下略
(controllers/api/sentences_controller.rb内) class Api::SentencesController < ApplicationController def top @sentences = Sentence.find_by(id:3) render 'top', formats: 'json', handlers: 'jbuilder' end end
(config/routes.rb内) Rails.application.routes.draw do ~~~ namespace :api do get 'top/:id' => 'sentences#top' ~~~ end end
試したこと
rails consoleにてDBにデータがあることは確認済み
@sentences = Sentence.find_by(id:3) (9.0ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483 Sentence Load (1.7ms) SELECT `sentences`.* FROM `sentences` WHERE `sentences`.`id` = 3 LIMIT 1 => #<Sentence id: 3, user_id: 1, source_id: 1, sentence: "hogehogehoge", created_at: "2018-12-15 20:18:03", updated_at: "2018-12-15 20:18:03"> irb(main):002:0>
補足情報(FW/ツールのバージョンなど)
rails 5.2.1
あなたの回答
tips
プレビュー