How to link form after creating rails join table

前端 未结 1 1106
谎友^
谎友^ 2021-01-15 03:34

Hi have a products model in my Rails 3.1 app which looked like this:

+----------------+---------------+------+-----+---------+----------------+
| Field              


        
相关标签:
1条回答
  • 2021-01-15 04:21

    A Product can have multiple Categories, and a Category can refer to multiple Products, right? If so, you want to create a third association table, let's call it product_categories, and use the standard Rails idioms to support it:

    # file: app/models/product.rb
    class Product < ActiveRecord::Base
      has_many :categories, :through => :product_categories
      has_many :product_categories, :dependent => :destroy
    end
    
    # file: app/models/category.rb
    class Category < ActiveRecord::Base
      has_many :products, :through => :product_categories
      has_many :product_categories, :dependent => :destroy
    end
    
    # file: app/models/product_category.rb
    class ProductCategory < ActiveRecord::Base
      belongs_to :product
      belongs_to :category
    end
    

    ... and your tables / migrations:

    # file: db/migrate/xxx_create_products.rb
    class CreateProducts < ActiveRecord::Migration
      def change
        create_table :products do |t|
          ... 
          t.timestamps
        end
      end
    end
    
    # file: db/migrate/xxx_create_categories.rb
    class CreateCategories < ActiveRecord::Migration
      def change
        create_table :categories do |t|
          t.string :name
          t.timestamps
        end
      end
    end
    
    # file: db/migrate/xxx_create_product_categories.rb
    class CreateProductCategories < ActiveRecord::Migration
      def change
        create_table :product_categories do |t|
          t.references :product
          t.references :category
          t.timestamps
        end
      end
    end
    

    This way, "adding multiple categories per product" becomes easy:

    my_product.categories.create(:name => "toy")
    

    This will create a Category named "toy" as well as the ProductCategory that associates my_product and that new Category. If you want the full description, this Guide is a place to start.

    0 讨论(0)
提交回复
热议问题