2016-05-16 151 views
0

我有三种模型:Deal,Zipcode,DealIncludeZipcode。Ruby on Rails嵌套表格

现在,联想看起来象下面这样: -

新政型号:

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.But时选择

现在我保存它没有保存的数据。

我已经使用迁移加入邮编和交易模型,其中我的排除邮政编码功能工作正常。

请提供一个soloution.I已经尝试了各种方法,但没有成功。

回答

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 
+0

我知道这一点,我用它们来排除邮编。 –

+0

我有一个包含邮编的功能。用户可以通过选择适用于Jquery的邮编来使用包含和排除邮编。在哪里以及如何保存包含邮政编码的数据作为联合表具有排除邮政编码的数据。 –

+0

我仍然认为你不明白 - 你的代码根本不使用DealIncludeZipcode模型,因为关系被定义为错误的。 – max

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,在那里你会找到更多的解释。

+0

我知道,我有这些+我有一个额外的表名DealIncludeZipcode。 –

+0

那么为什么不直接使用DealIncludeZipcode作为联合表呢? – Zino

+0

我的意思是,使用has_and_belongs_to_many关联的关键是创建一个联合表,该联合表不包含关联本身以外的任何信息。如果你有更多的信息或逻辑需要进入该协会,那么只需使用has_many .. through ..可能会更好地为您服务。 – Zino