Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 嵌套属性更新在观察者中触发错误回调_Ruby On Rails_Observers - Fatal编程技术网

Ruby on rails 嵌套属性更新在观察者中触发错误回调

Ruby on rails 嵌套属性更新在观察者中触发错误回调,ruby-on-rails,observers,Ruby On Rails,Observers,应用程序/模型中有两个类: class Job accepts_nested_attributes_for :address end class Address end 然后在jobs\u controller,update方法中,我执行@job.update(job\u params),在表单提交的job\u params中包含地址参数 地址可以正确更新,但是地址观察者的行为不正常。相反,当地址被更新时,它实际上会在创建后触发 address_observer.rb # cannot

应用程序/模型中有两个类:

class Job
  accepts_nested_attributes_for :address
end

class Address
end
然后在
jobs\u controller
update
方法中,我执行
@job.update(job\u params)
,在表单提交的job\u params中包含地址参数

地址可以正确更新,但是地址观察者的行为不正常。相反,当地址被更新时,它实际上会在创建后触发

address_observer.rb

# cannot be triggered when address gets updated
def after_update(address)
end

# can be triggered when address gets updated
def after_create(address)
end

不知道为什么,任何人都可以在这方面提供帮助?非常感谢。

在您的情况下,您需要确保您的参数是通过一个键
address\u attributes
传入的,并且是正确的
id
。如果不包括
id
,将创建一条记录。这就是为什么在\u create
之后触发
,而不是在\u update
之后触发

下面是一个示例(假设
有一个
关系:)

以下是相关文件:

现在,您可以通过成员的属性哈希设置或更新相关帖子的属性:include the key:posts\u attributes,并将帖子属性的哈希数组作为值。 对于没有id键的每个哈希,将实例化一个新记录[…]


而不是观察者..在模型中使用回调

after_commit :add_count_in_profile, on: :create


def add_count_in_profile
  Rails.logger.info  "---------updating images count in the profile for #
end

谢谢!我只需要在控制器参数require中传递permit
id
。而且我没有意识到它每次都创建一个新记录,因为db中的地址计数没有改变。我只是仔细阅读了控制台日志,发现rails实际上删除了旧地址,并用新的
id
创建了一个新地址@Shane:这很有趣。我不知道这种行为,但我会警告我的同事。
after_commit :add_count_in_profile, on: :create


def add_count_in_profile
  Rails.logger.info  "---------updating images count in the profile for #
end