2014-01-23 72 views
0

我跟着這LINKhas_many:通過不保存協會

但它不保存關聯。

我的模型是:

class Shift < ActiveRecord::Base 
     has_many :week_shifts, :dependent => :destroy 
     has_many :weeks, :through => :week_shifts, :dependent => :destroy  
     accepts_nested_attributes_for :weeks 
    end 

    class Week < ActiveRecord::Base 
     has_many :week_shifts, :dependent => :destroy 
     has_many :shifts, through: :week_shifts, :dependent => :destroy 
    end 

    class WeekShift < ActiveRecord::Base 
     belongs_to :week 
     belongs_to :shift 
    end 

和_form是:

<% @weeks = Week.find(:all) %> 
    <% @weeks.each do |week| %> 
    <div class="field"> 
    <%= check_box_tag 'week_ids[]', week.id, @shift.weeks.include?(week) %> 
    <%= week.day %> 
    </div> 
    <% end %> 
    <%= hidden_field_tag 'week_ids[]', '' %> 

輸出是這個

渲染偏移/佈局內edit.html.erb /應用( 109.3ms) 在119ms內完成200 OK(查看:44.4ms | ActiveRecord:73.0ms) 啓動PATCH「/移位/ 3 「爲127.8.96.129於2014-01-23 06:46:58 -0500通過ShiftsController處理#更新爲HTML參數:{」utf8「=>」✓「, 」authenticity_token「=>」Ltd3Ln5YJcRf40wQiPeGC + rRVeeGTpU + X1pUGjxbN6M =「, 」shift「=> {」cod「=>」CN「,」nome「=>」Centrale Notte「,」descr「=>」Operatore Centrale Notte「,」stato「=>」1「 「inizio(4i)」=>「00」,「inizio(5i)」=>「00」, 「fine(4i)」=>「08」 「week_ids」=> [「1」,「2」,「3」,「4」, 「」],「commit」=>「Update Shift」,「id」=>「3」}

回答

0

看起來您需要限制您的表單的輸入爲week_ids,以便它們構成shift PARAMS的一部分。目前,它的發佈是這樣的:

{ 
    "shift"=>{ 
    "cod"=>"CN", 
    "nome"=>"Centrale Notte", 
    "descr"=>"Operatore Centrale Notte", 
    "stato"=>"1", 
    "inizio(4i)"=>"00", 
    "inizio(5i)"=>"00", 
    "fine(4i)"=>"08", 
    "fine(5i)"=>"00" 
    }, 
    "week_ids"=>["1", "2", "3", "4", ""] 
} 

而應該是這樣的:

{ 
    "shift"=>{ 
    "cod"=>"CN", 
    "nome"=>"Centrale Notte", 
    "descr"=>"Operatore Centrale Notte", 
    "stato"=>"1", 
    "inizio(4i)"=>"00", 
    "inizio(5i)"=>"00", 
    "fine(4i)"=>"08", 
    "fine(5i)"=>"00", 
    "week_ids"=>["1", "2", "3", "4", ""] 
    } 
} 

所以你的形式,應該有這個代替:

<%= check_box_tag 'shift[week_ids][]', week.id, @shift.weeks.include?(week) %>