سؤال

So I have two tables, "houses" and "landowners". "houses" has a column named "landowner_id", such that on the site when someone adds a house they can optionally specify the owner_id. Thus,

class House < ActiveRecord::Base
  belongs_to :landowner

and

class LandOwner < ActiveRecord::Base
  has_many :houses, dependent: :nullify

I am using the dependent: :nullify above in order to have my tables set up in such a way that when I delete an owner record that I have previously added, it then deletes the landowner_id from any houses that have the same landowner_id as the id of the owner that was deleted. However, it won't delete the landowner_id record.

هل كانت مفيدة؟

المحلول

You should be using dependent: :destroy

class LandOwner < ActiveRecord::Base
  has_many :houses, dependent: :destroy

Then you can do @landowner.destroy,which would delete all the houses that are associated with that landowner.

From the Guides, :nullify causes the foreign keys to be set to NULL.While :destroy causes all the associated objects to also be destroyed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top