我试图做到这一点,以便当用户点击几行代码时提交-每行将成为新资源,例如:
User inputs:
Code1
Code2
Code3
Code4
They hit submit
Now 4 new resources have been made for the code model
我读到另一个问题,我可以使用“拆分”方法,该方法是通过在“ \ n”上拆分它来尝试的,但是这种方法不起作用,由于某种原因,它试图进入创建视图并抛出错误。
这是我到目前为止的内容:
##Controllers/codes_controller.rb (partial)
class CodesController < ApplicationController
############################################
#CREATING#
############################################
def new
@code = Code.new
end
def create
array2 = code_params[:code].split("\n")
array2.each do |f|
@code = Code.new(params[f])
if @code.save
flash[:notice] = "Codes added"
redirec_to(:action => 'index')
else
render('new')
end
end
end
private
def code_params
params.require(:code).permit(:id, :user_id, :code, :created_at, :updated_at)
end
end
我的表格
#views/codes/new.html.erb
<%= simple_form_for @code do |f| %>
<%= f.input :code, :label => "Codes (make sure each one is on a new line)", :input_html => { :rows => 50, :cols => 75 } %>
<%= f.button :submit %>
<% end %>
我将如何做到这一点,从而做到我正在尝试的?
更新**
由于某种原因,错误消息已更改-这是我现在得到的错误:
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
同样,它似乎正在保存一些代码,但实际上并没有保存有关该代码的任何信息(例如实际代码),而是仅创建一个带有ID的新代码,仅此而已。
您的代码几乎没有问题,因为:
因此,您需要在回车符上拆分代码,并且由于您想一次保存多个代码并同时显示错误或成功消息,因此可以添加添加标记以跟踪失败的添加操作,或者添加一个数组@erroneous_codes
或附加其中失败的代码。最后,您可以检查数组是否为空,这意味着已添加所有代码。
def create
array2 = code_params[:code].split("\r\n")
@erroneous_codes = []
array2.each do |f|
@code = Code.new(code: f)
@erroneous_codes << f unless @code.save
end
if @erroneous_codes.blank?
flash[:notice] = "All Codes are added successfully"
redirect_to(:action => 'index')
else
flash[:error] = "Some codes could not be added: #{@erroneous_codes.join(', ')}"
render('new')
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句