Join table for has_many through in Rails

后端 未结 2 1658
庸人自扰
庸人自扰 2021-02-13 22:04

I am new to programming & rails and there\'s something I dont fully understand. I am creating an app with

product has_many categories
category has_many produ         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 22:37

    You also have to add CategoryProduct to each model:

    class Product < ActiveRecord::Base
      has_many :category_products
      has_many :categories, through: :category_product
    

    It is very simple using gem simple form. All you have to do is to add:

    t.association :categories
    

    in a form for product and add :category_ids => [] to a list of permitted parameters in your products controller

    If you prefer checkboxes instead of multi-select list, you can do

        t.association :categories, as: check_boxes
    

    And the last thing, to display categories in human-readable format, you need to define a to_s method in your category model, i. e.:

    class Category < ActiveRecord::Base
      ...
      def to_s
        name
      end 
    end
    

提交回复
热议问题