简体   繁体   English

Rails-将JSON从视图传递到控制器

[英]Rails - passing a JSON from a view into a controller

In my Rails app, I would like to pass a Javscript array into the new action controller - the array is created from user input in one of the other views, and is composed of JSONs. 在我的Rails应用程序中,我想将Javscript数组传递到new动作控制器中-该数组是从其他视图之一中的用户输入创建的,并且由JSON组成。 What is the best method to a) pass the array of JSONs to the controller, and b) parse the array in the controller so that I can do things like get the array length, render the JSONs into the new view, etc.? 最好的方法是什么:a)将JSON数组传递给控制器​​,以及b)解析控制器中的数组,以便执行诸如获取数组长度,将JSON呈现到new视图等操作。

As I have built it, the app works fine, but I can see that the way that I have done things will cause problems as I continue to develop it. 在构建它的过程中,该应用程序运行良好,但是我可以看到,随着我的不断发展,我做事的方式会引起问题。

Currently, my action controller looks like this: 目前,我的动作控制器如下所示:

def new

    x = Integer(params[:total_inserts_param])

    @report_group = Array.new
    x.times do
      @report_group.push(Report.new)
    end
end

where total_inserts_param is a count of the array length calculated in the preceding view and passed in via URL, while the actual content of the JSONs are passed between the views via stringified localStorage objects; 其中total_inserts_param是在前一个视图中计算并通过URL传递的数组长度的计数,而JSON的实际内容是通过字符串化的localStorage对象在视图之间传递的; the content of those objects is parsed out and inserted into the variable number of form input fields in the new view generated by the controller. 这些对象的内容将被解析并插入到控制器生成的new视图中的可变数量的表单输入字段中。 This is certainly one way to pass data around a Rails app, but I'm pretty sure it's not a very good way! 当然,这是在Rails应用程序中传递数据的一种方法,但是我敢肯定这不是一个很好的方法!

I would much rather get the array into the controller, generate a Report.new for each JSON in the array, then populate the input fields created by the controller with the attributes of the JSONs. 我更希望将数组放入控制器,为数组中的每个JSON生成一个Report.new ,然后使用JSON的属性填充由控制器创建的输入字段。

I'm fairly new to Rails, so any insight into how to approach this would be much appreciated. 我对Rails还是很陌生,所以对如何解决此问题有任何见解。

What is the best method to 什么是最好的方法

a) pass the array of JSONs to the controller, a)将JSON数组传递给控制器​​,

the array is created from user input in one of the other views, 该数组是根据其他视图之一中的用户输入创建的,

Why not submit that form to the target action, then use ruby to assemble the data into an array? 为什么不将该表单提交给目标操作,然后使用ruby将数据组装成一个数组? If that isn't an option, you can use javascript to send an ajax request to your rails app. 如果不是这样,则可以使用javascript将ajax请求发送到Rails应用。 Here it is using coffeescript and jquery: 在这里,它使用coffeescript和jquery:

window.my_func = () ->  #`window` is needed if you call the function from another file  

  array = [1, 2, 3]
  text = JSON.stringify { my_array: array }

  ajax_settings = 
    type: "post",
    url: 'http://localhost:3000/dogs/dostuff', 
    data: text,  
    contentType: "application/json",
    success: (response) -> 
        $("#result").html(response)

  $.ajax(ajax_settings)

When you write jquery code, there are so many annoying braces and parentheses, you should consider using coffeescript instead: 当您编写jquery代码时,有很多烦人的花括号和括号,您应该考虑使用coffeescript代替:

coffee script syntax 咖啡脚本语法
coffee script syntax and jquery 咖啡脚本语法和jQuery

That coffeescript goes in your app/assets/javascript/controller_name.js.coffee file, which is automatically created by rails when you create a controller. 该coffeescript进入您的app / assets / javascript / controller_name.js.coffee文件,该文件在创建控制器时由rails自动创建。 In my case, I used a controller named DogsController, so the coffeescript file is app/assets/javascript/dogs.js.coffee. 就我而言,我使用了一个名为DogsController的控制器,因此coffeescript文件为app / assets / javascript / dogs.js.coffee。

Then, in your application.html.erb layout, you include the one big minified js file that rails creates from all the individual js files, like this: 然后,在application.html.erb布局中,包含rails从所有单个js文件创建的一个大的缩小的js文件,如下所示:

<!DOCTYPE html>
<html>
<head>
  <meta charset="ISO-8859-1">
  <title>Restauranteur</title>
  <%= stylesheet_link_tag    "application", media: "all" %>
  <%= javascript_include_tag "application" %>  <**** HERE *****
  <%= csrf_meta_tags %>
</head>
<body>

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

<div>Application Layout</div>

<div>
  <%= yield %>
</div>

<%= debug params %>
<%= debug session[:allowed] %>
</body>
</html>

To call my_func() in one of your views, you just need to write: 要在其中一种视图中调用my_func() ,只需编写以下代码:

<script>
my_func();
</script>

b) parse the array in the controller so that I can do things like get the array length b)在控制器中解析数组,以便执行诸如获取数组长度的操作

Ruby has a standard library module for converting JSON text into a ruby hash so that you can easily retrieve the data: Ruby有一个标准的库模块,用于将JSON文本转换为ruby哈希,以便您可以轻松地检索数据:

http://ruby-doc.org/stdlib-2.3.1/libdoc/json/rdoc/JSON.html#method-c-5B-5D http://ruby-doc.org/stdlib-2.3.1/libdoc/json/rdoc/JSON.html#method-c-5B-5D

However, in your rails app you don't even need to write any code to convert the JSON text into a hash: in your jquery ajax request if you specify the contentType to be "application/json" , then rails will automatically convert the JSON text in the request into a hash, which will be available in params : 但是,在Rails应用程序中,您甚至不需要编写任何代码即可将JSON文本转换为哈希值:在jquery ajax请求中,如果将contentType指定为"application/json" ,则Rails会自动将JSON转换将请求中的文本转换为散列,可在params

{"my_array"=>[1, 2, 3], "controller"=>"dogs", "action"=>"dostuff", "dog"=>{}}  

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

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