私のレールアプリからJSON APIを呼び出しています。ユーザーがフォームに名前を入力すると、JSON APIが呼び出され、名前に一致するものがあるかどうかがわかります。時にはその1つで、私はJSONで提供されるデータでエントリを作成します。しかし、ほとんどの場合、JSONには複数の結果があります。どのように実装するのですか?同じ名前の複数の結果が見つかりました。どちらをお探しですか?ユーザーは自分が意図していたものを選択し、データベースにエントリを作成します。レールで確認やプレビューを実装する方法は?
私はJSONをテストするための簡単なスクリプトを書いています。
data = JSON.load response
if data['results'].empty?
#if the JSON data is empty
puts "There was no movie found. Did you spell the movie name correctly?"
elsif data['results'].count > 1
#if JSON Data has more than one result
data['results'].each do |movie|
Movie::Movies << Movie.new(movie['id'],
movie['title'],
movie['release_year'],
(imdb_url + movie['imdb']).to_s,
movie['rating'],
movie['poster_120x171'],
movie['poster_240x342'],
movie['poster_400x570'])
end
Movie::Movies.each do |movie|
puts "#{movie.title} : #{movie.release_year}"
end
else
#IF JSON has only one entry
movie = Movie.new(data['results'][0]['id'],
data['results'][0]['title'],
data['results'][0]['release_year'],
(imdb_url + data['results'][0]['imdb']).to_s,
data['results'][0]['rating'],
data['results'][0]['poster_120x171'],
data['results'][0]['poster_240x342'],
data['results'][0]['poster_400x570'])
end
ここに私のコントローラがあります。 JSONが提供するハッシュの最初のレコードしか処理できません。私は、複数の結果がある場合、状況をどのように処理するかについての手がかりはありません。私のフォームは私にエラーを与えていたので、私は再び@movie = Movie.new
を呼び出すために持っていたアクションを作成中にも
def create
require 'rest_client'
require 'json'
imdb_url = 'http://www.imdb.com/title/'
movie_title = movie_params['title'].delete(' ')
response = RestClient.get "http://api-public.guidebox.com/v1.43/US/xxxxxxxxxxxxxxxx<api-key>/search/movie/title/#{movie_title}"
data = JSON.load response
@movie = Movie.new #i am doing this because my for was giving error.
if data['results'].empty?
flash[:alert] = "Did you spell the Title correctly? Or Maybe we could not find the movie you are looking for."
render 'new'
elsif data['results'].count > 2
#Display all results to the user for them to pick what they really intended and create an entry of whaterver they choose.
else
@movie = Movie.new(gb_id: data['results'][0]['id'],
title: data['results'][0]['title'],
release_year: data['results'][0]['release_year'],
imdb_link: (imdb_url + data['results'][0]['imdb']).to_s,
rating: data['results'][0]['rating'],
small_img: data['results'][0]['poster_120x171'],
med_img: data['results'][0]['poster_240x342'],
large_img: data['results'][0]['poster_400x570'])
if @movie.save
flash[:notice] = 'Movie has been successfully Added.'
redirect_to @movie
else
flash[:alert] = "Something went wrong. Please try again."
render 'new'
end
end
end
。
これは、組織的にはかなり邪魔になっています。あなたの 'require'呼び出しをファイルの先頭に移動します。それらはメソッドの中に属しません。くぼみを一定にして清潔に保ちます。 – tadman
通常、使用するパターンは '@ movie.save!'です。次に 'ActiveRecord :: RecordInvalid'をレスキューします。 – tadman