0

I want to add some category for my Rails post app.

I want them as fixed value so user can choose from the drop down menu the specific category. My migration file looks like this:

class CreateCategories < ActiveRecord::Migration[5.1]
  def change
    create_table :categories do |t|
      t.string :name
      t.timestamps
    end
  end
end

What do I have to do to add some fixed value in my categories model?

1
  • What database are you using? Commented Jun 15, 2017 at 16:56

2 Answers 2

1

You could set constant like NAMES = %w(category1 category2) inside Category model, add inclusion validation and get values for your dropdown like this: Category::NAMES. In this case don't forget to add database index. Obviously you will query posts related to some category.

There is another option though provided by ActiveRecord::Enum. It lets you declare category field right inside Post without Category model at all. If you don't need to manage categories outside the codebase (some admin panel), I would recommend this:

class Post < ActiveRecord::Base
  enum category: [:category1, :category2]
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your answer. I didn't know about the 'ActiveRecord::Enum' and I was looking for something like this :)
0

If you want to add some predefined categories, then this is called "seed data": Migrations and Seed data.

To add initial data after a database is created, Rails has a built-in 'seeds' feature that makes the process quick and easy. This is especially useful when reloading the database frequently in development and test environments. It's easy to get started with this feature: just fill up db/seeds.rb with some Ruby code, and run rails db:seed:

Category.create(name: 'category 1')
Category.create(name: 'category 2')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.