首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails autosave提供双重验证错误。

Rails autosave提供双重验证错误。
EN

Stack Overflow用户
提问于 2015-07-14 08:51:40
回答 2查看 333关注 0票数 0

我正在使用Rails 4.2。

我有四种型号:

代码语言:javascript
复制
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

代码语言:javascript
复制
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选项并运行如下代码:

代码语言:javascript
复制
user = User.new
user.licenses.build(...)
user.save

用户对象两次获取每个验证错误。

我在做什么奇怪的事吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-08-19 12:51:09

这是Rails中的一个bug,参见:https://github.com/rails/rails/issues/20874

票数 0
EN

Stack Overflow用户

发布于 2015-07-14 09:15:04

您应该从belongs_to中删除autosave: true。它也会自动保存许可。因为你增加了自动保存。它正在运行两次验证。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31402039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档