关于协会

时间:2017-03-24 00:29:39

标签: ruby-on-rails model-associations

我有3个型号。所有者,财产和租客。 我对Renter协会感到困惑,因为在我的房地产系统中,租户可以拥有多个租赁房产。 也许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

1 个答案:

答案 0 :(得分:0)

我不认为你需要一个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