我實現在軌一個程序,其中有一個表單並提交表單後,它會檢查是否有與數據庫中的特定字段重複值的任何記錄陣列面臨的問題。我的數據庫表是學生。所以我相應的型號名稱是學生。我在我的控制器中編寫了這個代碼(我剛剛討論過)。 但我面臨以下錯誤。我正在使用一些數組進行內部操作。當我僅在Ruby中寫入特定函數(不是rails)時,它工作正常。此外,由於使用「長度」,我也面臨錯誤。有關在軌
我的錯誤是: NoMethodError在StudentsController#創建
未定義的方法`[]」爲零:NilClass
我的控制器的代碼:
class StudentsController < ApplicationController
def new
@student=Student.new
@students=Student.all
end
def create
@student=Student.new(u_params)
ret_val=string_check
if ret_val==1
@student.save
redirect_to new_student_path , :notice => "Inserted!!!"
else
redirect_to new_student_path , :notice => "Match,Not inserted!!!"
end
end
def u_params
params.require(:student).permit(:id ,:firstname, :lastname)
end
def u_params_second
params.require(:student).permit(:firstname)
end
def string_check
count =0;
#temp1=:firstname
temp1=params[:firstname]
supplied_val=temp1
puts "Entered in string_check method"
for i in 46..100
temp2=Student.find_by(id:i)
table_val=temp2.firstname
size1=supplied_val.to_s.length
size2=table_val.to_s.length
arr1=Array.new
arr2=Array.new
# arr1[i] ||= []
# arr2[i] ||= []
for i in 0..size1
arr1.push(supplied_val[i])
end
for i in 0..size2
arr2.push(table_val[i])
end
for i in 0..size1
if arr1[i]=="@" || arr1[i]=="#" || arr1[i]=="{" || arr1[i]=="}" || arr1[i]=="(" || arr1[i]==")" || arr1[i]=="[" || arr1[i]=="]" || arr1[i]=="." || arr1[i]==";" || arr1[i]=="," || arr1[i]=="%" || arr1[i]=="&" || arr1[i]=="*" || arr1[i]=="!" || arr1[i]=="?" || arr1[i]=="$" || arr1[i]=="^" || arr1[i]==":" || arr1[i]=="-" || arr1[i]=="/"
count=count+1
# puts count
arr1[i]=""
end
end
# puts arr1
puts arr1.join
final1=arr1.join
for i in 0..size2
if arr2[i]=="@" || arr2[i]=="#" || arr2[i]=="{" || arr2[i]=="}" || arr2[i]=="(" || arr2[i]==")" || arr2[i]=="[" || arr2[i]=="]" || arr2[i]=="." || arr2[i]==";" || arr2[i]=="," || arr2[i]=="%" || arr2[i]=="&" || arr2[i]=="*" || arr2[i]=="!" || arr2[i]=="?" || arr2[i]=="$" || arr2[i]=="^" || arr2[i]==":" || arr2[i]=="-" || arr2[i]=="/"
count=count+1
# puts count
arr2[i]=""
end
end
# puts arr2
puts arr2.join
final2=arr2.join
if final1==final2
flag=0
else
flag=1
end
return flag
end
end
end
的routes.rb中文件:
Rails.application.routes.draw do
resources :students
end
讓我看看你的路線和視圖文件,並做「#{@ student.to_json}」 –
你可以分享你在哪一行得到'nil:NilClass'錯誤的未定義方法'[]'的細節? –
與您的問題無關,但請考慮使用Array#Include?而不是長期的ORs。例如'if [「@」,「#」,「{」,... etc] .include?(arr1 [i])' – Nimir