【问题标题】:Does rails scaffold command support generate belongs_to or many to many model middle table migration info?rails scaffold 命令是否支持生成belongs_to 或多对多模型中间表迁移信息?
【发布时间】:2011-05-02 17:00:48
【问题描述】:

Product,Category 是 rails3 上的两个模型,它们之间的关系如下:

产品有_and_belongs_to_many 类别

类别 has_and_belongs_to_many 产品

我可以使用脚手架为这两个模型生成迁移

rails g scaffold product name:string
rails g scaffold category name:string

但是如何生成多对多模型的中间表迁移信息,或者我需要手动编写,如果这对我来说很难,希望有人可以帮助我。

【问题讨论】:

  • guides.rubyonrails.org/…我找到了一些有用的链接,似乎需要自己创建关联表,如果这样的话,我认为rails不是那么神奇
  • en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord/… 我还找到了另一个相关链接,我还有一个问题是如何命名关联表,products_categories 或 categories_products,如果两个模型都以 c 或 p 字符开头,则将哪个模型名称放在关联中-表名

标签: ruby-on-rails scaffold rails-generate


【解决方案1】:

你需要自己创建这个表

   create_table :products_categories, :id => false do |t| 
     t.integer :product_id 
     t.integer :category_id
   end

警告,您需要将 :id 定义为 false,因为此表不需要 id 列。如果您有 id 列,则该表无法在 has_and_belongs_to_many 上使用。

【讨论】:

    【解决方案2】:
    rails g model ProductCategories product:references category:references
    

    【讨论】:

    • 不应该是ProductsCategories吗?
    • 我认为ProductCategories ?
    猜你喜欢
    • 2013-12-14
    • 2011-06-17
    • 2023-03-21
    • 2012-10-15
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多