has_one,reject_if和accept_nested_attributes_for仍会触发验证

时间:2014-05-27 14:09:58

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

我试图为帐户设置单一服务登录位置,但不要求帐户所有者每次更新其余记录时都输入服务登录凭据。

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

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

我是否正确理解:reject_if has_one关联?

父模型代码:

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

1 个答案:

答案 0 :(得分:0)

好吧,我的主要观点似乎是试图验证: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
相关问题