let me first start by saying this could also be a modeling problem and I am open to model suggestions.
Use Case: I have a form and I need to allow a user to select a checkbox on the category of their post. If there is no category that fits their post checking the other category will show a text field for the user to add a custom category.
DB Modeling
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name, null: false
t.timestamps null: false
end
reversible do |dir|
dir.up {
Category.create(name: 'Hats')
Category.create(name: 'Shirts')
Category.create(name: 'Pants')
Category.create(name: 'Shoes')
Category.create(name: 'Other')
}
end
create_table :posts_categories, id: false do |t|
t.belongs_to :post, index: true, null: false
t.belongs_to :category, index: true, null: false
t.string :value
end
end
end
App Models
class Post < ActiveRecord::Base
has_and_belongs_to_many :categories
accepts_nested_attributes_for :categories, allow_destroy: true
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :posts
end
This all works great, but I don't know where the text field will fit in for when the category is other. Not sure where a good place to store it would be. I have ran through a polymorphic relationship as well be get stuck with how it all works. If there is a better way to model this please, share.
Aucun commentaire:
Enregistrer un commentaire