Ruby on Rails嵌套表格
问题描述:
我有三种模型: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已经尝试了各种方法,但没有成功。
答
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
答
我认为马克斯的权利。所以,你的迁移应该是
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,在那里你会找到更多的解释。
我知道这一点,我用它们来排除邮编。 –
我有一个包含邮编的功能。用户可以通过选择适用于Jquery的邮编来使用包含和排除邮编。在哪里以及如何保存包含邮政编码的数据作为联合表具有排除邮政编码的数据。 –
我仍然认为你不明白 - 你的代码根本不使用DealIncludeZipcode模型,因为关系被定义为错误的。 – max