何時間もの間、私はこれを機能させようとしています
class Player < ActiveRecord::Base
has_many :signature_heroes, :through => :signature_heros, :source => :hero, :dependent => :destroy
has_many :signature_heros
accepts_nested_attributes_for :signature_heros
has_many :heros, :through => :details
end
class SignatureHero < ActiveRecord::Base
belongs_to :player
belongs_to :hero
end
class Hero < ActiveRecord::Base
has_many :details
has_many :signature_players, :through => :signature_heros, :source => :player, :dependent => :destroy
has_many :signature_heros
has_many :players, :through => :details
end
# players_controller
# GET /players/new
def new
@player = Player.new
signature_hero = @player.signature_heros.build
end
def player_params
params.require(:player).permit(:name, :account_id, :team_id, signature_heros_attributes: [:id, :player_id, :hero_id])
end
これらは私のモデルです。
<%= form_for(@player) do |f| %>
<div class="field">
<%= collection_select(:player, :team_id, Team.all, :id, :name, { :include_blank => true }, class: "form-control" ) %>
</div>
<%= f.fields_for :signature_heros do |s| %>
<div class="field">
<%= collection_select(:signature_hero, :hero_id, Hero.all, :id, :name, { :include_blank => true }, class: "form-control" ) %>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :account_id %><br>
<%= f.number_field :account_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
送信ボタンをクリックして新しいものを保存するとPlayer
、Player
それ自体は保存されますが、多対多の関係は保存されません。それはレールサーバーの出力です
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gMQTrtoKCmyZoVfP34DUbU6Arzu9DQ+IrHiFC68QH8I=", "player"=>{"team_id"=>"", "name"=>"qwqweqwe", "account_id"=>"111111"}, "signature_hero"=>{"hero_id"=>"1"}, "commit"=>"Create Player"}
(0.1ms) BEGIN
Player Exists (0.3ms) SELECT 1 AS one FROM `players` WHERE `players`.`account_id` = BINARY 111111 LIMIT 1
SQL (0.2ms) INSERT INTO `players` (`account_id`, `name`) VALUES (111111, 'qwqweqwe')
(13.2ms) COMMIT