Rails模型回调不起作用(创建另一个类的新实例)

时间:2021-05-03 22:31:21

In my circuit.rb class I have the following

在我的circuit.rb类中,我有以下内容

class Circuit < ActiveRecord::Base

  after_create :create_service

  def create_service
    # create service record
    service = Service.new :service_type => 'Circuit', :child_id => self.id, :organisation_id => self.organisation_id
  end

I only want the callback to fire when the circuit is created, I've tried before_validation aswell, no errors in the log, in fact, there is no mention of the services table being touched, I've restarted the server aswell just as a precaution but not sure why the service instance isn't being saved.

我只希望在创建电路时触发回调,我已经尝试过before_validation,日志中没有错误,事实上,没有提到要触摸的服务表,我重新启动了服务器以及预防措施但不确定为什么没有保存服务实例。

For completeness:

为了完整性:

class CircuitController < ApplicationController
  def update
    ...
    if request.post?
      if @circuit
        # update
      else
        # attempt create
        @circuit = Circuit.new params[:circuit]
        if @circuit.save
          redirect_to :action => 'update', :id => @circuit.id
        end
      end
    end
  end
end

Also, all columns in the table allow NULL, except the id column which is AUTO_INCREMENT anyway so there's nothing on the database side that would prevent a record being saved, similarly there is no validation in the model and the circuit is saved properly.

此外,表中的所有列都允许NULL,除了id列,无论如何都是AUTO_INCREMENT,因此数据库端没有任何东西可以阻止记录被保存,类似地,模型中没有验证并且电路被正确保存。

1 个解决方案

#1


3  

Your callback is probably firing properly. The problem is that you're setting up a new Service, but not actually saving it. When your controller redirects, the Circuit object is reloaded and loses the Service object.

您的回调可能正常启动。问题是您正在设置新服务,但实际上并未保存它。当控制器重定向时,将重新加载Circuit对象并丢失Service对象。

You probably want to actually create the object:

您可能想要实际创建对象:

service = Service.create :service_type => 'Circuit', :child_id => self.id, :organisation_id => self.organisation_id

#1


3  

Your callback is probably firing properly. The problem is that you're setting up a new Service, but not actually saving it. When your controller redirects, the Circuit object is reloaded and loses the Service object.

您的回调可能正常启动。问题是您正在设置新服务,但实际上并未保存它。当控制器重定向时,将重新加载Circuit对象并丢失Service对象。

You probably want to actually create the object:

您可能想要实际创建对象:

service = Service.create :service_type => 'Circuit', :child_id => self.id, :organisation_id => self.organisation_id