我不确定说出这个或使用条款的最佳方式,但我试图以正确的方式保存到连接表。 我希望能够创建一个新团队,其中包含与该团队相关联的玩家以及与锦标赛相关联的团队。我的模型如下:
tournament.rb
class Tournament < ApplicationRecord
has_many :team_players
has_many :teams, through: :team_players
has_many :users, through: :team_players
end
team_player.rb
class TeamPlayer < ApplicationRecord
belongs_to :team
belongs_to :user
belongs_to :tournament
end
team.rb
class Team < ApplicationRecord
has_many :team_players
has_many :users, through: :team_players
has_many :tournaments, through: :team_players
end
user.rb
class User < ApplicationRecord
has_many :team_players
has_many :tournaments, through: :team_players
has_many :teams, through: :team_players
end
这是我目前正在尝试的但是得到以下错误,因为它显然也需要用户,但我不知道如何将它传递给current_user。
tournaments_controller.rb
@tournament.teams.new(name: tournament_params[:new_team_name])
@tournament.save!
错误:验证失败:用户必须存在
答案 0 :(得分:0)
BluGeni,您可以在模型中使用accepts_nested_attributes_for。这样可以在创建Tournament
并为Team
分配User
时更轻松地创建Team
。
以下是accepts_nested_attributes_for
class User < ApplicationRecord
has_many :photos
accept_nested_attributes_for :photos
end
class Photo < ApplicationRecord
belongs_to :user
end
# Initializing an User and the Photo associated to the user
user = User.new(photos_attributes: { some_attribute: "a value" } )
user.save # Create the User and the Photo
# Creating an User and the photo associated to the user
User.create(photos_attributes: { some_attribute: "a value" } )