Ruby on Rails嵌套表单

时间:2016-05-16 11:34:01

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

我有三种型号:Deal,Zipcode,DealIncludeZipcode。

现在,该协会如下所示: -

交易模式:

class Deal < ActiveRecord::Base
  has_many  :deal_include_zipcodes, dependent: :destroy
  has_and_belongs_to_many  :zipcodes, dependent: :destroy

  accepts_nested_attributes_for :deal_include_zipcodes,:reject_if => :reject_include_zipcodes, allow_destroy: true

  private
    def reject_include_zipcodes(attributes)
      if attributes[:deal_id].blank? || attributes[:zipcode_id].blank?
        if attributes[:id].present?
          attributes.merge!({:_destroy => 1}) && false
        else
          true
        end
      end
    end
end

class Zipcode < ActiveRecord::Base
  has_and_belongs_to_many :deals
end


class DealIncludeZipcode < ActiveRecord::Base
    belongs_to :deal
    belongs_to :zipcode
end

现在在视图中我有一个复选框,取消选中它我可以选择多个邮政编码从DealIncludeZipcode中选择。但是当我保存数据时它没有保存。

我使用迁移来加入Zipcode和Deal Model,其中我的排除邮政编码功能正常运行。

请提供解决方案。我尝试了各种方法但没有成功。

2 个答案:

答案 0 :(得分:0)

has_and_belongs_to_many的重点是你没有一个加入这两个部分的模型。

class Deal < ActiveRecord::Base
  has_and_belongs_to_many :zipcodes
end

class Zipcode < ActiveRecord::Base
  has_and_belongs_to_many :deals
end

将通过名为deals_zipcodes的“无头”表加入。如果您想要加入模型,则需要使用has_many :through

class Deal < ActiveRecord::Base
  has_many :deal_zipcodes, dependent: :destroy
  has_many :zipcodes, through: :deal_zipcodes
end

class DealZipcode < ActiveRecord::Base
  belongs_to :deal
  belongs_to :zipcode
end

class Zipcode < ActiveRecord::Base
  has_many :deal_zipcodes, dependent: :destroy
  has_many :deals, through: :deal_zipcodes
end

答案 1 :(得分:0)

我认为马克斯是对的。所以你的迁移应该是

create_table :deals do |t|
  t.string :name
  ...
end
create_table :zipcodes do |t|
  t.string :zipcode
  ...
end
create_table :deals_zipcodes do |t|
  t.belongs_to :deal, index: true
  t.belongs_to :zipcode, index: true
end

你的模特应该是

class Deal < ActiveRecord::Base
  has_and_belongs_to_many :zipcodes
end
class Zipcode < ActiveRecord::Base
  has_and_belongs_to_many :deals
end

您应该查看ActiveRecord guide,在那里您可以找到更多解释。