سؤال

i have follow this LINK

but it not saving associations.

My Model are:

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

and the _form is:

  <% @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[]', '' %>

the output is this

Rendered shifts/edit.html.erb within layouts/application (109.3ms) Completed 200 OK in 119ms (Views: 44.4ms | ActiveRecord: 73.0ms) Started PATCH "/shifts/3" for 127.8.96.129 at 2014-01-23 06:46:58 -0500 Processing by ShiftsController#update as HTML Parameters: {"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", "fine(5i)"=>"00"}, "week_ids"=>["1", "2", "3", "4", ""], "commit"=>"Update Shift", "id"=>"3"}

هل كانت مفيدة؟

المحلول

Looks like you need to qualify your form's inputs for the week_ids, so that they they form part of the shift params. At the moment it is posting like this:

{
  "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", ""]
}

Whereas it should be like:

{
  "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", ""]
  }
}

So your form should have this instead:

<%= check_box_tag 'shift[week_ids][]', week.id, @shift.weeks.include?(week) %>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top