Reputation: 1167
I am trying different methods of creating categories in rails 4 to just see what works the best, so far I am not having much joy. I do not want to use a gem to create this as thats not the answer.
I have a set of events that I want to categorize.
Can anyone suggest the best and most convenient way of getting this right?
Thanks
Upvotes: 1
Views: 348
Reputation: 76784
We've created a set of categories for our system recently, and was relatively simple. Just use a has_and_belongs_to_many
:
#app/models/category.rb
Class Category < ActiveRecord::Base
has_and_belongs_to_many :events
end
#app/models/event.rb
Class Event < ActiveRecord::Base
has_and_belongs_to_many :categories
end
Schemas:
categories
id | name | created_at | updated_at
events
id | name | created_at | updated_at
categories_events
category_id | event_id
This will allow you to call things like this:
#app/controllers/events_controller.rb
def add_category
@event = Event.find(params[:id])
@category = Category.find(params[:category_id])
@event.categories << @category #->> as to be two ActiveRecord objects
end
Heres my code update
admin/category.rb
ActiveAdmin.register Category do
controller do
def permitted_params
params.permit category: [:name]
end
def find_resource
scoped_collection.friendly.find(params[:name])
end
end
form do |f|
f.inputs "Details" do
f.input :name
end
f.actions
end
end
models/category.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :events
end
admin/event.rb
ActiveAdmin.register Event do
controller do
def permitted_params
params.permit event: [:title, :slug, :event_image, :category, :eventdate, :description]
end
def find_resource
scoped_collection.friendly.find(params[:id])
end
def index
@events = current_category.events
end
end
form do |f|
f.inputs "Details" do
f.input :title
end
f.inputs "Event Date" do
f.input :eventdate, :date_select => true, :as => :date_picker, :use_month_names => true
end
f.inputs "Category" do
f.input :categories, :as => :select, :collection => Category.all
end
f.inputs "Biography" do
f.input :description, :as => :ckeditor, :label => false, :input_html => { :ckeditor => { :toolbar => 'Full', :height => 400 } }
end
f.inputs "Image" do
f.file_field :event_image
end
f.actions
end
end
model/event.rb
class Event < ActiveRecord::Base
has_and_belongs_to_many :categories
has_attached_file :event_image, styles: {
large: "600x450#",
medium: "250x250#",
small: "100x100#"
}, :default_url => "/images/:style/filler.png"
validates_attachment_content_type :event_image, :content_type => /\Aimage\/.*\Z/
validates :title, :slug, :event_image, presence: true
extend FriendlyId
friendly_id :title, use: :slugged
end
Upvotes: 2