0

几个小时我都在努力完成这项工作

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它本身会被保存,但多对多关系不会。那是rails服务器输出

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
4

1 回答 1

0

将选择标签更改signature_hero

 <%= s.collection_select( :hero_id, Hero.all, :id, :name, { :include_blank => true }, class: "form-control" ) %>

如果没有s.将参数传递给控制器"signature_hero"=>{"hero_id"=>"1"}​​,那么它们应该是"signature_hero_attributes"=>{"hero_id"=>"1"}

于 2013-09-20T18:50:34.990 回答