我有3個表格:超級英雄,權力,團隊rails 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
如你剛纔提到的那樣,你需要使用after_save鉤子的可能性很低, 。這似乎是錯誤的:'@power_team = PowerTeam.new(params [:power_ids] [:team_ids])',因爲它會假設請求參數'power_id'可以使用鍵':power_ids'訪問,並返回一個散列用一個關鍵字':team_ids',這幾乎肯定不是這種情況。另外,如果沒有使用的模式或表單代碼等,它需要大量的假設和猜測才能提供幫助,因此可能有助於將該信息添加到您的問題中。 –