Problem with Active Record in Rails and setting relationships
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开发者_StackOverflow中文版_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
solved it by myself, just added self.reload
after the creation of the relationship. Now it returns the created relationship within the first request.
精彩评论