Rails 中的 Active Record 问题和设置关系

发布于 2024-10-10 02:27:25 字数 997 浏览 0 评论 0原文

我目前在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随心而道 2024-10-17 02:27:25

我自己解决了这个问题,只需在创建关系后添加 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文