JSON文件为空,但保存了值

时间:2015-08-24 06:56:18

标签: ruby-on-rails json

我试图将输入保存到我的数据库并在我的JSON文件中显示,以便我可以在我的网站上输出它。当我在输入中键入名称然后单击保存操作时,一切都会正常。没有错误,当我检查rails控制台时,我得到了,

from -e:1:in `<main>'irb(main):002:0> Movie.last
  Movie Load (2.9ms)  SELECT  "movies".* FROM "movies"  ORDER BY "movies"."id" DESC LIMIT 1
=> #<Movie id: 5, created_at: "2015-08-24 06:37:46", updated_at: "2015-08-24 06:37:46", user_id: nil, image: nil, title: "Star Wars", release_date: nil>

我目前保存的唯一数据是标题。

但是当我访问http://localhost:3000/movies.json输出时,

[null,null,null,null,null,null,null]

数据库中有7个id,当我添加另一个时,json输出给出8次null。

那么为什么我的输入没有显示在JSON输出中?

的routes.rb

resources :movies, only: [:create, :index, :show]

movies_controller.rb

class MoviesController < ApplicationController

  def index
    respond_with Movie.all
  end

  def create
    respond_with Movie.create(movie_params)
  end

  private
  def movie_params
    params.require(:movie).permit(:title)
  end

end

2 个答案:

答案 0 :(得分:0)

您是否尝试过以下操作?我希望这会帮助你。

class MoviesController < ApplicationController

  def index
    @movies = Movie.all
    respond_to do |format|
      format.html
      format.json { render json: @movies }
    end
  end

  def create
    respond_with Movie.create(movie_params)
  end

  private
  def movie_params
    params.require(:movie).permit(:title)
  end
end

答案 1 :(得分:0)

您需要在顶部respond_to

class MoviesController < ApplicationController
  respond_to :json, :html

  def index
    respond_with Movie.all
  end

  def create
    respond_with Movie.create(movie_params)
  end

  private
  def movie_params
    params.require(:movie).permit(:title)
  end

end

http://asciicasts.com/episodes/224-controllers-in-rails-3