我在rails web应用程序上有一个ruby,但我希望它像Web服务一样行事,而不是HTML来返回JSON。我想要所有的CRUD方法。我希望整个页面被渲染为JSON,到目前为止,我只在User
变量的显示和编辑中实现了这一点。但是我想要整个页面,所有CRUD方法都显示为JSON。Rails返回JSON而不是HTML
def index
@users = User.all
end
def show
@user = User.find(params[:id])
# Render json or not
render json: @user
end
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
end
def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render 'new'
end
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to users_path
end
到目前为止,我发现这个render json: @user
,但我想整个页面呈现为JSON而不仅仅是变量。和所有CRUD方法的每个URL。编辑:如果我添加到我的routes.rb
类似这样的东西resources :users, defaults: {format: :json}
然后我得到错误消息“缺少模板用户/索引,应用程序/索引与{:locale => [:en],:formats => [:json] ,:变种=> []:处理程序=> [:ERB,:建设者,:生,:红宝石,:咖啡:JBuilder中]}”
是否有可能没有专门调用URL中的.json JSON呈现?例如http:// localhost:3000/users等等它会自动显示JSON? – Whizzil
所以如果你只需要JSON,你必须像你意识到的那样做。在你写资源的路由中:用户,默认值:{format:'json'}。并在控制器呈现json:@user或@users。如果没有帮助,只显示你本地服务器在控制台中返回的内容 – IgorLeonenko