【发布时间】: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