【问题标题】:has_many :through not saving associationshas_many :通过不保存关联
【发布时间】:2014-01-23 11:48:37
【问题描述】:

我已经关注这个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[]', '' %>

输出是这样的

在布局/应用程序中渲染 shifts/edit.html.erb (109.3ms) 在 119 毫秒内完成 200 次 OK(查看次数:44.4 毫秒 | ActiveRecord:73.0 毫秒) 在 2014-01-23 06:46:58 为 127.8.96.129 开始 PATCH "/shifts/3" -0500 由 ShiftsController#update 处理为 HTML 参数:{"utf8"=>"✓", "authenticity_token"=>"Ltd3Ln5YJcRf40wQiPeGC+rRVeeGTpU+X1pUGjxbN6M=", "shift"=>{"cod"=>"CN", "nome"=>"Centrale Notte", "descr"=>"Operator Centrale Notte", "stato"=>"1", "inizio(4i)"=>"00", "inizio(5i)"=>"00", "fine(4i)"=>"08", "fine(5i)"=>"00"}, "week_ids"=>["1", "2", "3", "4", ""], "commit"=>"更新班次", "id"=>"3"}

【问题讨论】:

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


    【解决方案1】:

    看起来您需要为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) %>
    

    【讨论】:

      猜你喜欢
      • 2015-12-13
      • 2013-11-24
      • 2016-08-24
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      相关资源
      最近更新 更多