2016-05-16 148 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