我有 3 张桌子:超级英雄、权力、团队
超级英雄可以拥有许多权力和许多团队。
例如:
superhero.rb
name:string
has_many :power_teams, :dependent => :destroy
has_many :powers, :through => :power_teams, :foreign_key => :power_id
has_many :teams, :through => :power_teams, :foreign_key => :team_id
power.rb
name:string
has_many :power_teams, :dependent => :destroy
team.rb
name:string
has_many :power_teams, :dependent => :destroy
#This is what I want to add to
power_team
belongs_to :superhero
belongs_to :power
belongs_to :team
更新这里是超级英雄的控制器
def create
@hero = Superhero.new(params[:hero])
形式:
<%= form_for(@hero) do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %>
#Teams are a drop-down, you can only choose 1 team
<%= f.collection_select(:team_ids, Team.all(:order=>:name), :id, :name, {:prompt => true}) %>
#powers are checkboxes, you can choose multiple powers
<% Power.all.each do |power| %>
<label class="checkbox">
<%= check_box_tag "superhero[power_ids][]", power.id, @hero.power_ids.include?(power.id) %>
<%= power.name %>
</label>
<% end %>
<% end %>
当我保存时,我得到了 1 个团队和 2 个权力(在索引页面中):
Hero | Power | Team
1 1
1 2
1 1
这是正确的吗?我以为我会看到并期待这个:
Hero | Power | Team
1 1 1
1 2 1