简体   繁体   中英

Rails Active record has:one relationship is allowing more than one

I have a one to one relationship between a projection model and player model. A team has_many players and has_many projections through: players.

I want to make it so that once a player is created and belongs_to a projection and a team that you can no longer create any players associated with that projection. Right now I can somehow create multiple players with the same projection id even though the projections have a has:one relationship with players. I thought this has_one relationship would prevent this??

Here is my form and models for creating a player. Please help:)!

<%= 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

You can enforce this at the database level by adding an index to the players table which requires project_id to be unique.

bundle exec rails g migration UniqueIdx

That creates the migration template, and then something like:

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

Then run the migration

bundle exec rails db:migrate

You should also enforce this on the model.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM