Rails 5 _ids数组的赋值在has_many上失败:通过关联

时间:2016-08-17 08:49:15

标签: ruby-on-rails activerecord

当从Rails 3.2升级到Rails 5时,我遇到了一个模型突然拒绝保存的问题。

我有2个模型:ClosingDayLocation,它们通过ClosingDayLocation模型具有has_many:through关系。创建ClosingDay时,用户需要使用复选框选择一个或多个Location记录。

但是,无论我在表单上选择哪些Location条记录,我都会在保存ClosingDay记录时收到错误消息,告诉我关联的ClosingDayLocation无效,因为{{1}是空的。

型号:

closing_day_id

控制器

class ClosingDay < ActiveRecord::Base
  has_many :closing_day_locations, :dependent => :destroy
  has_many :locations, :through => :closing_day_locations
end

class Location < ActiveRecord::Base
  has_many :closing_day_locations, :dependent => :destroy
  has_many :closing_days, :through => :closing_day_locations
end

class ClosingDayLocation < ActiveRecord::Base
  belongs_to :location
  belongs_to :closing_day

  validates :closing_day_id, :presence => true
  validates :location_id, :presence => true
end

表格

  def create
    @closing_day = ClosingDay.build(closing_day_params)

    if @closing_day.save
      redirect_to(closing_days_url, :notice => 'OK')
    else
      @locations = Location.active.order(:name)
      render :action => 'new'
    end
  end

  private
  def closing_day_params
    params.require(:closing_day).permit(:date, :name, location_ids: [])
  end

简而言之,我想创建一个新的<%= form_for(@closing_day) do |f| %> <%= show_errors_for(@closing_day) %> <table> <tr> <td><%= f.label :name %></td> <td><%= f.text_field :name %></td> </tr> <tr> <td><%= f.label :date %></td> <td><%= f.text_field :date %></td> </tr> <tr> <td><%= label_tag 'closing_day[location_ids][]', 'Locations' %></td> <td> <%= hidden_field_tag 'closing_day[location_ids][]', nil %> <% @locations.each do |location| %> <p> <%= label_tag do %> <%= check_box_tag 'closing_day[location_ids][]', location.id, @closing_day.location_ids.include?(location.id) %> <%= location.name %> <% end %> </p> <% end %> </td> </tr> <tr> <td colspan="2"><%= f.submit %></td> </tr> </table> <% end %> 记录,并通过基本上使用@closing_day分配Location ID来分配关联的(预先存在的)位置。这适用于Rails 3.2,但似乎在Rails 5中不起作用。

保持此功能的最佳方法是什么?我还尝试添加@closing_day.location_ids = [3,6,9]accepts_nested_attributes_for :locations, :allow_destroy => true,但这似乎不起作用。似乎已创建关联的accepts_nested_attributes_for :closing_day_locations, :allow_destroy => true模型,但ClosingDayLocation仍为空,从而导致错误。

1 个答案:

答案 0 :(得分:1)

经过一些修修补补后,我发现了问题并解决了问题。我会在这里分享,以防其他人遇到同样的问题!

class ClosingDayLocation < ActiveRecord::Base
  belongs_to :location
  belongs_to :closing_day

  #validates :closing_day_id, :presence => true
  #validates :location_id, :presence => true
end

在中间模型上删除这两个验证后,它对创建和更新都很好。显然,验证和保存相关记录的一些顺序已在Rails 3.2和Rails 5之间转移。