未定义的方法`map'为“1,2”:字符串

时间:2016-03-31 14:48:26

标签: ruby-on-rails reactjs

我需要在一个参数中传递一个数组,可能吗?例如,值可以是["1","2","3","4","5"],这些是字符串,但需要稍后将其转换为整数。

我在rails form_for之间使用react_component。 html是这样的:

<input type="hidden" name="people_id" id="people_id" value={this.state.people} />

人物阵列看起来像这样:

enter image description here

如何在隐藏字段的value中传递数组?我得到的服务器错误是

我试图在模型中做这样的事情:

ids = params[:people_id]

ids.map do |b|
  Foo.create!(people_id: b.to_i)
end

如果我ids.split(",").map我得到符号到int错误。

编辑:

----------------------------------------------- -----------

仍然不确定问题是什么,因为没有任何作用。这是我的代码的最小再现:

This answer is my react component这就是我添加到数组的方式。仍然在组件中,我有隐藏的字段:

<input type="hidden" name="[people_id][]" id="people_id" value={this.state.people} />

_form.html.erb:

<%= form_for resource, as: resource_name, url: registration_path(resource_name), :html => { :data => {:abide => ''}, :multipart => true } do |f| %>
 <!-- react component goes here -->
 <%= f.submit  "Go", class: "large button" %>
<% end %> 

故事是,客人可以一次性注册时选择少数人。注册完成后,将通知这些人。把它想象成“我邀请这些人竞标我的投标”。数组中的这些数字是user_id s。

用户/ registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  # POST /resource
  def create
   super do |resource|
    ids = params[:people_id].pop # logs now as "people_id"=>["1,2"]
    resource.save!(ids.split(",").map |b| Foo.create!(people_id: b.to_i) end)
   end
  end
end

resource.save行上的新错误:

  

没有将符号隐式转换为整数

编辑#2

如果我只有,create方法:

ids.split(",").map do |b|
 resource.save!(Foo.create!(people_id: b.to_i))
end

有效!使用正确的Foo创建people_id两次。

因为我正在创建更多对象:Bar,我不知道该怎么做:

 resource.save!(<the loop for Foo> && Bar.create!())

流程必须是:

  1. 设备创建用户
  2. 使用循环
  3. 创建Foo
  4. 创建了条
  5. 必须以这种方式完成,因为用户对象是动态创建的。

1 个答案:

答案 0 :(得分:0)

在Rails中,您可以使用末尾括号的参数键来传递数组。

但是,您不应将值连接为逗号分隔列表,而是将每个值作为单独的参数发送:

GET /foo?people_ids[]=1&people_ids[]=2&people_ids[]=3

这样Rails会将参数解压缩到一个数组中:

Parameters: {"people_ids"=>["1", "2", "3"]}

同样的原则适用于POST,除了params作为formdata发送。

如果你想要一个如何运作的好例子,那么看一下rails collection_check_boxes助手及其产生的输入。

<input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
<label for="post_author_ids_1">D. Heinemeier Hansson</label>
<input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
<label for="post_author_ids_2">D. Thomas</label>
<input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
<label for="post_author_ids_3">M. Clark</label>
<input name="post[author_ids][]" type="hidden" value="" />

更新

如果您打算通过拆分字符串来实现自己的数组参数,则不应使用括号结束输入:

<input type="hidden" name="[people_id][]" value="1,2,3">
{"people_id"=>["1,2,3"]} 

注意people_id如何被视为数组,输入值是第一个元素。

虽然你可以做params[:people_id].first.split(",")但是从get go中使用正确的密钥更有意义:

<input type="hidden" name="people_id" value="1,2,3">

另外,你真的不想包装&#34; root&#34;括号中的键。这是在rails中用于在散列中嵌套param键,例如。 user[name]