prafull purwar
prafull purwar

Reputation: 39

Ruby on Rails Nested Form

I have three Models: Deal, Zipcode, DealIncludeZipcode.

Now, the association looks like below:-

Deal Model:

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

Now in view I have a checkbox,on unchecking it I can select multiple zipcode to select from DealIncludeZipcode. But when I save the data it is not saving.

I have used migration for joining Zipcode and Deal Model in which my exclude zipcode functionality is working correctly.

Please provide a solution. I have tried various method but didn't succeed.

Upvotes: 0

Views: 228

Answers (2)

Zino
Zino

Reputation: 21

I think Max's right. So your migration should be

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

And your models should be

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

You should probably take a look at the ActiveRecord guide, where you'll find more explanation.

Upvotes: 0

max
max

Reputation: 102250

The whole point of has_and_belongs_to_many is that you don't have a model which joins the two parts.

class Deal < ActiveRecord::Base
  has_and_belongs_to_many :zipcodes
end

class Zipcode < ActiveRecord::Base
  has_and_belongs_to_many :deals
end

Would join through a "headless" table called deals_zipcodes. If you want to have a join model you need to use has_many :through instead.

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

Upvotes: 0

Related Questions