请教Rails中的create(attributes={})的问题

本文探讨了一个Rails应用中关于学生与班级关联创建的问题。作者尝试使用`create`和`build`方法来建立关联,但遇到了关联未正确创建的情况。通过分享具体的代码片段和日志信息,寻求社区的帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是添加student的代码
[code]
def add
@student = Student.new(params[:student])
@klass = Klass.find(:first, :conditions => [ "klass_num = ?" , params[:klass][:klass_num] ])
if @klass.students.create(@student.attributes)
flash[:notice] = "Student was successfully created"
redirect_to :action => :list
else
flash[:notice] = "Failed to create student!"
redirect_to :action => :add_student
end
end
[/code]
[code]
@klass.students.create(@student.attributes)
[/code]
这句本来不应该是把@student关联到@klass对象,并且保存新建的对象@student么?
但是结果并没有保存,弄了半天也没找出什么原因。
我把
[code]
if @klass.students.create(@student.attributes)
[/code]
我改成:
[code]
@klass.students.build(@student.attributes)
if @student.save
[/code]
保存是成功了,但是没有建立klass与student之间的关联,不知道到底哪儿有问题,希望大家指点一下
log中传递的参数是正确的:
Parameters: {"klass"=>{"klass_num"=>"210309"}, "commit"=>"添加", "action"=>"add", "controller"=>"student", "student"=>{"name"=>"fuliang", "password_confirmation"=>"123456", "student_num"=>"21030922", "password"=>"123456"}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值