How to create Categories in Rails

前端 未结 2 1228
遥遥无期
遥遥无期 2020-12-23 13:04

i\'m trying to Add Categories to my Rails app, but don\'t quite know how to do this.

I have many Pins(Images) and want the user to be able to assign a category on th

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 13:41

    First If you don't want to manage categories in your application, then you can simply add a category field in your table and category select in your application :

    <%= f.select :category, [ 'Box', 'Cover', 'Poster' ], :prompt => 'Select One' %>
    

    Second, If you want to manage categories in your application, than you have to maintain a separate model and table for it. So you can start with generating your model:

    rails g model category
    

    it will add model and migration in your application directory. Add stuff to your migration:

    class CreateCategories < ActiveRecord::Migration
      def change
        create_table :categories do |t|
          t.string :name
          t.text :description
          ## you can add more stuff as per your requirements 
          t.timestamps
        end
      end
    end
    

    Define associations in category & Pin model add validation for this :-

    In Category Model:
      has_many :pins
    
    In Pin Model :
      belongs_to :category
      validates :category, presence: true
    

    Create some categories by categories controller and form (I don't think, I need to tell you that stuff, you are able to do it yourself)

    In your pin uploading form add this select :-

    <%= f.select :category, Category.all, :prompt => "Select One" %>
    

    Hope, It will help.

提交回复
热议问题