Rails 中的 Active Record 问题和设置关系
我目前在 Rails 中有一个控制器,我在其中创建一个模型对象并设置与该模型对象的关系。我希望将该关系作为响应,但如果模型对象是在第一个请求中创建的,则该关系我将得到 nil 。在第一个请求之后,我将得到正确的关系作为响应。在创建对象模型后设置关系后是否必须更新模型对象?
我的代码:
控制器:
def create
@patient = Patient.find_or_create_by_prename_and_lastname_and_birthday(params[:patient])
@doctor = Doctor.find(current_user.id)
@patient.create_qr_code_from_doctor_if_no_exists(@doctor)
@qr_code = @patient.get_last_qr_code
respond_to do |format|
format.json {
render :json => @qr_code.to_json
}
end
end
型号:
def create_qr_code_from_doctor_if_no_exists(doctor)
if self.qr_codes.size == 0
QrCode.create!(:patient => self, :doctor => doctor)
end
end
def get_last_qr_code
if(self.qr_codes.size > 1) # sort only if there is more than one QR-Code
self.qr_codes.sort do |x,y|
y.created_at <=> x.created_at
end
end
self.qr_codes.at(0)
end
I currently have a controller in rails, where i create a model object and set a relationship to that model object. I want that relationship as a response, but if the model object gets created within the first request, i get nil for the relationship. After the first request I'll get the right relationship as a response. Do I have to update the model object after setting a relationship, just after creating the object model?
My code:
Controller:
def create
@patient = Patient.find_or_create_by_prename_and_lastname_and_birthday(params[:patient])
@doctor = Doctor.find(current_user.id)
@patient.create_qr_code_from_doctor_if_no_exists(@doctor)
@qr_code = @patient.get_last_qr_code
respond_to do |format|
format.json {
render :json => @qr_code.to_json
}
end
end
Model:
def create_qr_code_from_doctor_if_no_exists(doctor)
if self.qr_codes.size == 0
QrCode.create!(:patient => self, :doctor => doctor)
end
end
def get_last_qr_code
if(self.qr_codes.size > 1) # sort only if there is more than one QR-Code
self.qr_codes.sort do |x,y|
y.created_at <=> x.created_at
end
end
self.qr_codes.at(0)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己解决了这个问题,只需在创建关系后添加
self.reload
即可。现在它返回第一个请求中创建的关系。solved it by myself, just added
self.reload
after the creation of the relationship. Now it returns the created relationship within the first request.