【问题标题】:Rails Active record has:one relationship is allowing more than oneRails 活动记录有:一个关系允许多个
【发布时间】:2021-07-12 08:55:21
【问题描述】:

我在投影模型和玩家模型之间存在一对一的关系。一个团队有_many 的球员,并通过:球员有_many 的预测。

我想做到这一点,一旦创建了一个球员并属于一个投影和一个团队,您就不能再创建与该投影相关联的任何球员。现在我可以以某种方式创建多个具有相同投影 id 的玩家,即使这些投影与玩家有一个 has:one 关系。我认为这种 has_one 关系会阻止这种情况发生??

这是我创建玩家的表格和模型。请帮忙:)!

<%= simple_form_for [ @player ] do |f| %>
    <%= f.select :team_id, @teams.collect { |t| [ t.name, t.id ] } %>
    <%= f.input :projection_id, :as => :hidden, :input_html => { :value => @projection.id } %>
    <%= f.submit "Assign Team", class: "btn btn-primary" %>
<% end %>
class Player < ApplicationRecord
  belongs_to :projection
  belongs_to :team
end
class Projection < ApplicationRecord
  belongs_to :leauge 
  has_one :player, dependent: :destroy
  has_one :team, :through => :player
end
class Team < ApplicationRecord
  belongs_to :leauge
  has_many :players, dependent: :destroy
  has_many :projections, :through => :players

  validates :name, uniqueness: { scope: :leauge_id } 
  validates :name, presence: true
end

【问题讨论】:

  • 您可以添加唯一索引和/或验证具有投影 id 的播放器模型的唯一性

标签: ruby-on-rails database schema rails-activerecord


【解决方案1】:

您可以通过向要求 project_id 唯一的 player 表添加索引来在数据库级别强制执行此操作。

bundle exec rails g migration UniqueIdx

创建迁移模板,然后是:

# db/migrations/xyz-unique-idx.rb
class UniqueIdx < ActiveRecord::Migration[something.something]
    add_index :players, :project_id, unique: true
end

然后运行迁移

bundle exec rails db:migrate

您还应该在模型上强制执行此操作。

# app/models/player.rb
class Player < ApplicationRecord
    ...
    validates :project, unique: true
    ...
end

【讨论】:

  • 谢谢。我会研究更多关于唯一索引的信息!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
相关资源
最近更新 更多