has_many:通过不保存关联

时间:2014-01-23 11:48:38

标签: ruby ruby-on-rails-4 has-many

我已关注此LINK

但它没有保存关联。

我的模特是:

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

输出是这个

  

在布局/应用程序中渲染shift / edit.html.erb(109.3ms)   在119ms完成200 OK(浏览次数:44.4ms | ActiveRecord:73.0ms)   在2014-01-23 06:46:58开始为127.8.96.129开始PATCH“/ shifting / 3”   -0500由ShiftsController处理#update更新为HTML参数:{“utf8”=&gt;“✓”,   “authenticity_token”=&gt; “中Ltd3Ln5YJcRf40wQiPeGC + rRVeeGTpU + X1pUGjxbN6M =”,   “shift”=&gt; {“cod”=&gt;“CN”,“nome”=&gt;“Centrale Notte”,“descr”=&gt;“Operatore   Centrale Notte“,”stato“=&gt;”1“,”inizio(4i)“=&gt;”00“,”inizio(5i)“=&gt;”00“,   “fine(4i)”=&gt;“08”,“fine(5i)”=&gt;“00”},“week_ids”=&gt; [“1”,“2”,“3”,“4”,   “”],“提交”=&gt;“更新转换”,“id”=&gt;“3”}

1 个答案:

答案 0 :(得分:0)

您似乎需要对week_ids的表单输入进行限定,以便它们成为shift参数的一部分。目前它的发布方式如下:

{
  "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) %>