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
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!
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.