2016-05-16 8 views
0

私は3つのモデル:Deal、Zipcode、DealIncludeZipcodeを持っています。今 Ruby on Railsネストされたフォーム

は、関連は以下のようになります -

ディールモデル:

私は、それをオフに私はDealIncludeZipcode.Butときから選択するように、複数の郵便番号をチェックボックスを選択することができているビューで今すぐ
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 

保存していないデータは保存します。

私は除外Zipcode機能が正しく機能しているZipcodeとDeal Modelに参加するために移行を使用しました。

解決策を提供してください。私は様々な方法を試しましたが、成功しませんでした。

答えて

0

has_and_belongs_to_manyの全体のポイントは、2つの部分を結合するモデルがないということです。

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で動作する郵便番号を選択することにより、郵便番号を含めたり除外したりすることができます。 zipcodeを含めるためのデータを結合テーブルとして保存する場所と方法には、郵便番号を除外するデータがあります。 –

+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 

そして、あなたのモデルでなければなりませんあなたはおそらく、あなたがより多くの説明を見つけることができますActiveRecord guide、見てみる必要があります

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

でなければなりません。

+0

私はこれを知っています+私はもう一つテーブル名DealIncludeZipcodeを持っています。 –

+0

次に、DealIncludeZipcodeをジョイントテーブルとして使用するだけではどうですか? – Zino

+0

私はhas_and_belongs_to_manyアソシエーションを使用することの全ポイントは、アソシエーション自体以外の情報を保持していないジョイントテーブルを作成することです。あなたが協会に参加する必要がある追加の情報やロジックを持っているなら、おそらくhas_many .. through ..を使って、おそらくあなたをより良くするでしょう。 – Zino

関連する問題