关于关联



我有 3 个模型。业主,财产和承租人。我对租房者协会感到困惑,因为在我的房地产系统中,租户可以拥有多个租赁物业。也许has_many通过?如果是。如何实施?

class Proprietor < ApplicationRecord
  has_many :properties, dependent: :destroy
end
class Property < ApplicationRecord
  belongs_to :proprietor
end
class Renter < ApplicationRecord
end
class CreateProprietors < ActiveRecord::Migration[5.0]
  def change
    create_table :proprietors do |t|
      t.string :full_name
      t.string :email
      t.date :birthday
      t.string :social_security
      t.string :doc_id
      t.text :address
      t.string :zip_code
      t.timestamps
    end
  end
end
class CreateProperties < ActiveRecord::Migration[5.0]
  def change
    create_table :properties do |t|
      t.references :proprietor, foreign_key: true
      t.text :address
      t.string :zip_code
      t.integer :rooms
      t.integer :bedrooms
      t.integer :bathrooms
      t.integer :garage
      t.string :price
      t.boolean :published, defalt: false
      t.timestamps
    end
  end
end
class CreateRenters < ActiveRecord::Migration[5.0]
  def change
    create_table :renters do |t|
      t.string :full_name
      t.string :email
      t.date :birthday
      t.string :social_security
      t.string :doc_id
      t.timestamps
    end
  end
end

我认为你不需要对此进行has_many(除非房产可以有很多租房者,也可以有很多房客?

如果需要如您在问题中所述,这应该是可以实现的:

class Proprietor < ApplicationRecord
  has_many :properties, dependent: :destroy
end
class Property < ApplicationRecord
  belongs_to :proprietor
  belongs_to :renter
end
class Renter < ApplicationRecord
  has_many :properties
end
class CreateProprietors < ActiveRecord::Migration[5.0]
  def change
    create_table :proprietors do |t|
      t.string :full_name
      t.string :email
      t.date :birthday
      t.string :social_security
      t.string :doc_id
      t.text :address
      t.string :zip_code
      t.timestamps
    end
  end
end
class CreateProperties < ActiveRecord::Migration[5.0]
  def change
    create_table :properties do |t|
      t.references :proprietor, foreign_key: true
      t.references :renter, foreign_key: true
      t.text :address
      t.string :zip_code
      t.integer :rooms
      t.integer :bedrooms
      t.integer :bathrooms
      t.integer :garage
      t.string :price
      t.boolean :published, default: false
      t.timestamps
    end
  end
end
class CreateRenters < ActiveRecord::Migration[5.0]
  def change
    create_table :renters do |t|
      t.string :full_name
      t.string :email
      t.date :birthday
      t.string :social_security
      t.string :doc_id
      t.timestamps
    end
  end
end

相关内容

  • 没有找到相关文章

最新更新