Rails own_to 可选,但如果通过则检查是否存在

Pur*_*uit 4 activerecord ruby-on-rails ruby-on-rails-5

我有一个属性希望在 a 中是可选的,belongs_to因为用户不必立即属于团队。

class User < ActiveRecord::Base
  belongs_to :team, optional: true
end
Run Code Online (Sandbox Code Playgroud)

team_id未传入的情况下创建的用户:

irb(main):001:0> User.create()
D, [2019-08-16T18:56:53.961520 #1] DEBUG -- :    (0.4ms)  BEGIN
D, [2019-08-16T18:56:53.988354 #1] DEBUG -- :   SQL (0.7ms)  INSERT INTO "users" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", "2019-08-16 18:56:53.985875"], ["updated_at", "2019-08-16 18:56:53.985875"]]
D, [2019-08-16T18:56:54.017858 #1] DEBUG -- :    (1.0ms)  COMMIT
=> #<User id: 5, provider: nil, uid: nil, name: nil, email: nil, oauth_token: nil, oauth_expires_at: nil, created_at: "2019-08-16 18:56:53", updated_at: "2019-08-16 18:56:53", team_id: nil, pagerduty_id: nil, slack_user_id: nil, admin: false>
Run Code Online (Sandbox Code Playgroud)

这很好,但是当我为此用户传递 a 时, rails在创建用户记录之前team_id不会检查该记录是否存在于表中。teams这可能会导致team_id数据库中不存在的团队被通过teams

目前我们数据库中的团队:

D, [2019-08-16T18:57:10.745090 #1] DEBUG -- :   Team Load (0.8ms)  SELECT "teams".* FROM "teams"
=> #<ActiveRecord::Relation [#<Team id: 1, pagerduty_service_key: nil, pagerduty_id: nil, name: "something", slack_channel: nil, slack_usergroup: nil>]>
Run Code Online (Sandbox Code Playgroud)

team_id使用of创建用户2仍然有效:

User.create(team_id: 2)
D, [2019-08-16T18:59:12.776053 #1] DEBUG -- :    (1.7ms)  BEGIN
D, [2019-08-16T18:59:12.783799 #1] DEBUG -- :   SQL (1.3ms)  INSERT INTO "users" ("team_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["team_id", 2], ["created_at", "2019-08-16 18:59:12.777772"], ["updated_at", "2019-08-16 18:59:12.777772"]]
D, [2019-08-16T18:59:12.789468 #1] DEBUG -- :    (1.9ms)  COMMIT
=> #<User id: 6, provider: nil, uid: nil, name: nil, email: nil, oauth_token: nil, oauth_expires_at: nil, created_at: "2019-08-16 18:59:12", updated_at: "2019-08-16 18:59:12", team_id: 2, pagerduty_id: nil, slack_user_id: nil, admin: false>
Run Code Online (Sandbox Code Playgroud)

从模型中删除optional: true可以验证记录是否存在,但也使其NULL不再允许使用值。有没有一种 Rails 方法可以检查表team_id中是否存在teams,而无需在数据库级别添加外键?

eda*_*edl 6

不幸的是,使用optional选项它会关闭您的记录的存在验证,但您可以在模型中添加自定义验证:

class User < ActiveRecord::Base
  belongs_to :team, optional: true

  validates_presence_of :team, if: :team_id_present?

private

  def team_id_present?
    team_id.present?
  end
end
Run Code Online (Sandbox Code Playgroud)