2

Rails で 2 つのモデル間の関係を確立しようとしていますが、移行で何をする必要があるかを理解するのに苦労しています。どんな助けでも大歓迎です。

各ビジネスには、「自動車」や「レストランとバー」などのタイプ/カテゴリが必要です。

ビジネス.rb:

class Business < ActiveRecord::Base
  has_one :category, :foreign_key => "cid"
  attr_accessible :description, :email, :facebook, :foursquare, :google, :manager,
  :mobile, :name, :phone, :url, :yelp
end

Type.rb:

class Type < ActiveRecord::Base
  attr_accessible :cid, :category
  belongs_to :business
end

CreateTypes 移行ファイル:

class CreateTypes < ActiveRecord::Migration
  def change
    create_table :types do |t|
      t.integer :cid
      t.string :category
      t.references :business

      t.timestamps
    end
  add_index :types, :cid
 end
end

CreateBusinesses 移行ファイル:

class CreateBusinesses < ActiveRecord::Migration
  def change
    create_table :businesses do |t|
      t.string :name
      t.string :url
      t.string :phone
      t.string :manager
      t.string :email
      t.boolean :mobile
      t.boolean :foursquare
      t.boolean :facebook
      t.boolean :yelp
      t.boolean :google
      t.text :description
      t.integer :cid

      t.timestamps
    end
  end
end
4

2 に答える 2

4

Railsの命名規則を守るのが最も簡単です。正しく取得できれば、ビジネスはタイプ/カテゴリに属します。ビジネスにタイプを参照させます。ビジネス側にbelongs_toを追加し、タイプ/カテゴリ側にhas_manyを追加します。大まかにこのように:

class Business < ActiveRecord::Base
  attr_accessible :description, :email, :facebook, :foursquare, :google, :manager, :mobile, :name, :phone, :type_id, :url, :yelp
  belongs_to :type
end

class Type < ActiveRecord::Base
  has_many :businesses
end

class CreateTypes < ActiveRecord::Migration
  def change
    create_table :types do |t|
      t.string :category

      t.timestamps
    end
  end
end

class CreateBusinesses < ActiveRecord::Migration
  def change
    create_table :businesses do |t|
      t.string :name
      t.string :url
      t.string :phone
      t.string :manager
      t.string :email
      t.boolean :mobile
      t.boolean :foursquare
      t.boolean :facebook
      t.boolean :yelp
      t.boolean :google
      t.text :description
      t.integer :type_id

      t.timestamps
    end
  end
end
于 2012-06-16T18:48:17.087 に答える
0

外部キーとして設定するため、businessesテーブルには整数フィールドが必要です。cidテーブルにフィールドがあっtypesてはなりませんcidtypes.idフィールドは関係を作成するために使用されます。belongs_toメソッドにはオプションがないことに注意してくださいforeign_key。呼び出しから削除する必要があります。

理由なく外部キーの名前を変更しないことをお勧めします。外部キーを指定しない場合、デフォルトでtype_id.

于 2012-06-16T18:30:46.597 に答える