简体   繁体   English

Ruby On Rails-通过控制器将参数从前端传递到数据库

[英]Ruby On Rails - Pass parameters from front end to database through controllers

How to pass parameters from front end to back-end API in Ruby on Rails only through controllers? 如何仅通过控制器将参数从前端API传递到后端API? I do not want to use model or views for this. 我不想为此使用模型或视图。

I am using a Ruby Gem which captures some usage data which needs to be stored into the back end database. 我使用的是Ruby Gem,它捕获一些需要存储到后端数据库中的使用情况数据。

I have created a controller, to which the post parameters are sent, but I get an error saying view is not found. 我创建了一个控制器,将发布参数发送到该控制器,但是出现一个错误,提示找不到视图。

ActionView::MissingTemplate (Missing template usage_metrics/create, application/create with {:locale=>[:en], :formats=>[:json, :js, :html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :web_console_v2], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/home/local/www/cc2/cc_user-frontend/app/views"
  * "/home/local/.rvm/gems/ruby-2.2.3/gems/ckeditor-4.2.2/app/views"
):

You need to send the request in an appropriate format (ie json) and ensure the controller action responds to this. 您需要以适当的格式(即json)发送请求,并确保控制器操作对此做出响应。 At the moment it's trying to respond with html but not finding a template for this. 目前,它尝试使用html进行响应,但没有为此找到模板。

For example, in the action, after you've done what you need to do: 例如,在操作中,完成操作后,您需要执行以下操作:

respond_to do |format|
  format.json { render json: { whatever: is_needed_in_the_response } }
end

And you'll get your response that way. 这样您将得到答复。

Or if you don't need a response after parsing the params, you can use render nothing: true . 或者,如果您在解析参数后不需要响应,则可以使用render nothing: true

NB I think the newest versions Rails will respond with nothing / json if there's no template found. 注意:如果找不到模板,最新版本的Rails将不响应/ json。 Not sure how this affects you. 不知道这对您有何影响。

Hope that helps! 希望有帮助!

if you want to return some data as json you can use 如果您想将某些数据作为json返回,则可以使用

render json: data

but if you only want to return status 但是如果您只想返回状态

render json: {}, status: 200

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM