ruby-on-rails - Rails has_one 和belongs_to 迁移?

标签 ruby-on-rails migration belongs-to has-one

我正在尝试在 Rails 中的两个模型之间建立关系,但我无法弄清楚在迁移中需要做什么。非常感谢任何帮助。

我希望每个企业都有一个类型/类别,例如“汽车”或“餐厅和酒吧”。

业务.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

类型.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

最佳答案

遵守 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

关于ruby-on-rails - Rails has_one 和belongs_to 迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11065959/

相关文章:

ruby-on-rails - ruby rails : Find all departmentid from Users Table

ruby-on-rails - 我如何强制 ActiveRecord 重新加载一个类?

ruby-on-rails - Rails belongs_to 关联,作为集合的一部分时无法访问所有者的属性?

PHP/MySQL : Check if something 'belongs-to' something else?

ruby-on-rails - 重命名的 active_admin 资源的可选 belongs_to

ruby-on-rails - 如何在没有Web服务器的情况下在WWW上发布我的应用程序?

ruby-on-rails - 模型中的 rails url helper

php - 如何回显 Laravel 和 Artisan 中的控制台?

mysql - 错误异常 : Creating default object from empty value

ruby-on-rails - rvm和Capistrano:无法在Bitbucket “conq: repository access denied.”上克隆git存储库,但可以从服务器内部手动访问