我正在使用Rails 4.2。
我有四种型号:
class User < ActiveRecord::Base
belongs_to :organization
has_many :licenses
end
class License < ActiveRecord::Base
belongs_to :user #, autosave: true
end
class Organization < ActiveRecord::Base
has_many :users
end
class Application < ActiveRecord::Base
has_many :licenses
end然后,我有如下代码,用于为用户创建一个License:
def user
@_user ||= User.find(...)
end
def create_license
license = License.find_or_initialize_by(application: @application, user: user)
if license.user.organization.nil?
license.user.organization = @organization
end
if license.user.organization == @organization
license.expires_on = nil
license.save
else
license.errors.add(:user, "User belongs to different organization")
end
license
end这段代码的问题是,当我运行license.save时,它不会保存user对象,即组织不会被更改。
因此,我将belongs_to :user, autosave: true添加到License类中,以强制它也保存用户。在这种情况下,这是正常的。
但是,如果设置了autosave选项并运行如下代码:
user = User.new
user.licenses.build(...)
user.save用户对象两次获取每个验证错误。
我在做什么奇怪的事吗?
发布于 2015-08-19 12:51:09
这是Rails中的一个bug,参见:https://github.com/rails/rails/issues/20874
发布于 2015-07-14 09:15:04
您应该从belongs_to中删除autosave: true。它也会自动保存许可。因为你增加了自动保存。它正在运行两次验证。
https://stackoverflow.com/questions/31402039
复制相似问题