[英]has_one, reject_if, and accept_nested_attributes_for still triggers validation
I'm trying to provide a place to set a single service login for an account, yet not require that the account owner enter the service login credentials every time the rest of the record is updated. 我试图提供一个位置来为帐户设置单个服务登录名,但是不要求每次更新记录的其余部分时帐户所有者都输入服务登录凭据。
My understanding is that the :reject_if
option on accepts_nested_attributes_for
is the way to have the nested hash values ignored. 我的理解是,
accepts_nested_attributes_for
上的:reject_if
选项是忽略嵌套哈希值的方法。 Yet, in Rails 4.1, I'm getting a "password can't be blank". 但是,在Rails 4.1中,我遇到了“密码不能为空”的问题。
I've traced through the nested_attributes code and it seems to properly ignore the values, yet nothing I do to avoid the update works. 我已经跟踪了nested_attributes代码,它似乎正确地忽略了这些值,但是我没有做任何避免更新的工作。 I've even deleted the
web_service_user_attributes
hash from the params passed to update
, so I'm wondering if there is something else going on. 我什至从传递给
update
的参数中删除了web_service_user_attributes
哈希,所以我想知道是否还有其他事情发生。
Am I understanding :reject_if
correctly for a has_one
association? 我是否对
has_one
关联正确理解:reject_if
?
Parent model code: 父模型代码:
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
Child model code: 子模型代码:
class WebServiceUser
devise :database_authenticatable
belongs_to :account
validates_uniqueness_of :username
validates_presence_of :password, if: Proc.new{|wsu| !username.blank? }
end
Controller code: 控制器代码:
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
Ok, it appears that my primary goof was trying to validate the presence of :password
. 好的,看来我的主要傻瓜正在尝试验证
:password
的存在。 I really wanted to validate the length of the password if it existed. 我真的想验证密码的长度(如果存在)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.