Rails:保存后验证关联? [英] Rails: Validating association after save?

查看:40
本文介绍了Rails:保存后验证关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 模型,它有很多 roles.角色包含一个 user_id 字段,我想validate_presence_of

I have a User model which has many roles. Roles contains a user_id field, which I want to validate_presence_of

问题是:如果我在创建时为用户分配角色,验证将失败,因为没有设置 user_id.现在,我确实想验证 user_id 是否存在,但我需要在检查之前保存用户.

The issue is: if I assign a role to user upon create, the validation fails because no user_id is set. Now, I do want to validate that a user_id exists, but I need to save the user before checking that.

当前代码如下所示:

@user = User.new(params[:user])
@user.roles << Role.new(:name => 'Peon') unless @user.has_roles?
if @user.save
  # ...

我能想到的解决问题的唯一方法是禁用验证(我不想这样做)或双重保存到数据库中,这并不完全有效.

The only ways I can think of getting around the problem involves either disabling the validation, which I don't want to do, or double-saving to the DB, which isn't exactly efficient.

处理这个问题的标准方法是什么?

What's the standard way for handling this issue?

推荐答案

我认为如果您将代码更改为如下所示,您可以解决验证问题:

I think you can get around the validation problem if you change your code to look like this:

@user = User.new(params[:user])
@user.roles.new(:name => 'Peon') unless @user.has_roles?
if @user.save
  # ...

如果这不起作用,您可以尝试将验证更改为:

If that doesn't work, you could try changing you validation to this:

class Role < ActiveRecord::Base
  belongs_to :user
  validates :user_id, :presence => true, :unless => Proc.new() {|r| r.user}
end

这篇关于Rails:保存后验证关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆