我有一个休息api,即发送一个字符串。问题是我需要为id使用这个字符串(它总是一个数字),这需要是一个整数。我试图通过在收到字符串时将字符串转换为整数来实现此目的。这就是我一直在尝试做的事情,但是当我尝试时,我会收到以下列出的错误消息:
def create
respond_with @classroom = Classroom.create(classroom_params)
if @classroom.save
#do stuff
else
#do other stuff
end
end
def classroom_params
params.require(:classroom).permit(:period.to_i, :teacher.to_i, :subject.to_i)
end
这是错误:
NoMethodError (undefined method `to_i' for :period:Symbol):
app/controllers/api/v1/classroom_controller.rb:42:in `classroom_params'
app/controllers/api/v1/classroom_controller.rb:24:in `create'
答案 0 :(得分:2)
试试这个。 permit
方法需要允许的符号列表。您只能classroom_params.map(&:to_i)
,因为您希望所有参数都是整数。如果classroom_params
中有任何您想要的字符串,则必须明确地将所需的内容转换为整数。
def create
attributes = classroom_params
@classroom = Classroom.create(:teacher_id => attributes[:teacher].to_i,
:student_id => attributes[:student].to_i,
:subject_id => attributes[:subject].to_i)
respond_with
if @classroom.save
#do stuff
else
#do other stuff
end
end
def classroom_params
params.require(:classroom).permit(:period, :teacher, :subject)
end