使用has_many和belongs_to的多个关系保存记录

时间:2017-08-30 17:08:32

标签: ruby-on-rails ruby-on-rails-5

我不确定说出这个或使用条款的最佳方式,但我试图以正确的方式保存到连接表。 我希望能够创建一个新团队,其中包含与该团队相关联的玩家以及与锦标赛相关联的团队。我的模型如下:

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!

错误:验证失败:用户必须存在

1 个答案:

答案 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" } )