How to create Categories in Rails

前端 未结 2 1227
遥遥无期
遥遥无期 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:20

    you might wanna add a def to_s method on your Category model. I believe it will display some weird memory address code just by using plain Category.all on the f.select option. Everything else looks great!

    0 讨论(0)
  • 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.

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