【问题标题】:has_one, reject_if, and accept_nested_attributes_for still triggers validationhas_one、reject_if 和 accept_nested_attributes_for 仍会触发验证
【发布时间】:2014-05-27 14:09:57
【问题描述】:

我正在尝试提供一个位置来为帐户设置单个服务登录,但不要求帐户所有者在每次更新记录的其余部分时都输入服务登录凭据。

我的理解是accepts_nested_attributes_for 上的:reject_if 选项是忽略嵌套哈希值的方法。然而,在 Rails 4.1 中,我得到一个“密码不能为空”。

我已经跟踪了nested_attributes 代码,它似乎正确地忽略了这些值,但我没有采取任何措施来避免更新工作。我什至从传递给update 的参数中删除了web_service_user_attributes 哈希,所以我想知道是否还有其他事情发生。

对于has_one 关联,我是否正确理解:reject_if

父型号代码:

class Account
  has_one :web_service_user

  accepts_nested_attributes_for :web_service_user, :allow_destroy => true, :reject_if => :password_not_specified, :update_only => true

  def password_not_specified(attributes)
    attributes[:password].blank?
  end
end

儿童型号代码:

class WebServiceUser
  devise :database_authenticatable

  belongs_to :account

  validates_uniqueness_of :username
  validates_presence_of :password, if: Proc.new{|wsu| !username.blank? }
end

控制器代码:

def update
  respond_to do |format|
    if @licensee.update(account_params)
  #etc...
end

private
def account_params
  params.require(:account).permit(:name, :area_of_business, :address1, :address2, :city, :state_code, :zip, :website_url, :web_service_user_attributes => [:id, :username, :password, :_destroy])
end

【问题讨论】:

    标签: ruby-on-rails devise ruby-on-rails-4.1


    【解决方案1】:

    好的,看来我的主要错误是试图验证:password 的存在。我真的很想验证密码的长度(如果存在)。

    class WebServiceUser
      devise :database_authenticatable
    
      belongs_to :account
    
      validates_uniqueness_of :username
      validates_length_of :password, :minimum => 14, if: Proc.new { |u| !u.password.nil? }
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2012-01-26
      相关资源
      最近更新 更多