简体   繁体   English

Ruby on Rails从文本区域中的列表中保存多个子记录

[英]Ruby on Rails save multiple sub records from a list in a text area

I have scoured stack overflow for and answer to my problem but can't find one. 我已经搜寻了堆栈溢出问题并回答了我的问题,但找不到一个。 So I was hoping that someone else out there has tried what I want to do before. 所以我希望其他人已经尝试过我想做的事情。

I have a question model, which has many options. 我有一个问题模型,其中有很多选择。 What I want to do is allow the user to copy a list of options into a textarea as a return/new line separated list. 我想做的是允许用户将选项列表复制到textarea中,作为返回/换行分隔的列表。

ie a list of locations 即位置列表

London 伦敦
Paris 巴黎
New York 纽约
Singapore 新加坡
Sydney 悉尼

And then from the questions controller I want to get each of these items insert them in the options model. 然后,我要从问题控制器中获取所有这些项目,并将它们插入选项模型中。

What I can't work out is how I access the textarea element from the controller as there is no object name associated with it. 我无法解决的是如何从控制器访问textarea元素,因为没有与之关联的对象名称。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks Ben 谢谢本

One way to go about it is associate the textarea element with your 'options' attribute, and then write a function in your model to split it into an array. 一种解决方法是将textarea元素与“ options”属性相关联,然后在模型中编写一个函数以将其拆分为数组。

For example, in your view: 例如,在您看来:

<%= form_for @question do |f| %>
...
<%= f.text_field :options %>

Then in your controller: 然后在您的控制器中:

def create
  @question = Question.new(params[:question])

  ...
  @question.split_options

  ...
end

In the model, the split_options method could use Ruby's string split functions to return an array, which then gets saved. 在模型中, split_options方法可以使用Ruby的字符串拆分函数返回一个数组,然后将其保存。

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

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