我试图让它成为当用户点击几行代码提交时 - 每一行都将成为新资源,例如:
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的新代码,就是这样。
答案 0 :(得分:1)
您的代码几乎没有问题:
所以你需要在回车上拆分代码,因为你想一次保存多个代码并显示错误或成功消息,你可以添加一个标志来跟踪失败的添加或者有一个数组@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