-->

How to create Categories in Rails

2019-01-30 20:56发布

问题:

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 those Pins. ASSIGN not create, edit, or delete a Category, just selecting one for their Pin. Meaning that, When a user uploads a pin, he can choose from a dropdown list a Category.

Then, another user can choose from the Menu a Category, and ONLY the Pins in this Category will be listed.

How do i do this? Where to start ?

Thank you

回答1:

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.



回答2:

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!