在Rails 4中创建类别的最佳方法是什么?

时间:2014-03-13 10:07:19

标签: ruby-on-rails ruby-on-rails-4 categories has-many

我正在尝试在rails 4中创建类别的不同方法,看看哪种方法效果最好,到目前为止我没有太多的快乐。我不想使用gem来创建它,因为那不是答案。

我有一组我要分类的事件。

有人能建议最好,最方便的方法吗?

由于

1 个答案:

答案 0 :(得分:2)

我们最近为我们的系统创建了一组类别,并且相对简单。只需使用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

架构:

categories
id | name | created_at | updated_at

events 
id | name | created_at | updated_at

categories_events
category_id | event_id

这将允许您调用以下内容:

#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

继承我的代码更新

管理员/ 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

模型/ category.rb

class Category < ActiveRecord::Base

    has_and_belongs_to_many :events

end

管理员/ 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

模型/ 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
相关问题