在开发中,JSON数据正常显示,但在生产环境中显示不正确。
在开发中,JSON数据正常显示,但在生产环境中显示不正确。
这是我的routes.rb文件
namespace :api do get 'suggestions/jobs', to: "suggestions#jobs" end
我的控制器
class Api::SuggestionsController < ApplicationController def jobs @jobs = Job.job_title_search(params[:q]) #.select(:title, :label).distinct if @jobs.present? render json: @jobs, status: :ok else render json: "Not Found", status: :ok end end end
和模型
def self.job_title_search(q) where('title LIKE ?', "%#{q}%").select(:title, :label).distinct end
在开发环境中,例如localhost:3000/api/suggestions/jobs?q=dev
,数据示例如下:
[
{"id":null,"title":"React Native Developer","label":"Top label job"},
{"id":null,"title":"Android Developer","label":"Top label job"},
{"id":null,"title":"Business Development Representative","label":"Mid label job"},
{"id":null,"title":"Node.js Developer","label":"Top label job"}
]
这意味着它正常工作,但是当我部署到Heroku上,例如example.herokuapp.com/api/suggestions/jobs?q=dev
,出现如下错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
我知道有类似以下代码的"Not Found":
render json: "Not Found", status: :ok
我的问题是为什么相同的代码在Heroku上无法工作?我应该怎么做?
database.yml文件内容如下:
# SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: sqlite3 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 development: <<: *default database: db/development.sqlite3 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: db/test.sqlite3 production: <<: *default database: my_project_production username: my_project password: <%= ENV['MY_PROJECT_DATABASE_PASSWORD'] %>
感谢任何帮助。谢谢。
问题出现的原因是在开发环境下,使用SQLite数据库,而在生产环境下,使用PostgreSQL数据库。在SQL中,使用了LIKE关键字进行查询。在开发环境中,LIKE关键字正常工作,而在生产环境中,LIKE关键字不起作用,而应该使用ILIKE关键字。然而,ILIKE关键字在SQLite中不起作用。
解决方法有两种:
解决方法1:将开发环境的数据库切换为PostgreSQL。如果对切换数据库有顾虑,可以尝试以下解决方法2。
解决方法2:使用lower(attr)函数,例如:
def self.job_title_search(q) where('lower(title) LIKE lower(?)', "%#{q}%").select(:title, :label).distinct end
可以参考这个Stack Overflow回答。
希望对你有帮助。