views:

208

answers:

2

In my Rails project I'm using Formtastic to manage my forms. I have a model, Tags, with a column, "group". The group column is just a simple hardcoded way to organize my tags. I will post my Tag model class so you can see how it's organized

class Tag < ActiveRecord::Base
  class Group
    BRAND     = 1
    SEASON    = 2
    OCCASION  = 3
    CONDITION = 4
    SUBCATEGORY = 5
  end

  has_many :taggings, :dependent => :destroy
  has_many :plaggs, :through => :taggings
  has_many :monitorings, :as => :monitorizable

  validates_presence_of :name, :group
  validates_uniqueness_of :name, :case_sensitive => false

  def self.brands(options = {})
    self.all({ :conditions => { :group => Group::BRAND } }.merge(options))
  end

  def self.seasons(options = {})
    self.all({ :conditions => { :group => Group::SEASON } }.merge(options))
  end

  def self.occasions(options = {})
    self.all({ :conditions => { :group => Group::OCCASION } }.merge(options))
  end

  def self.conditions(options = {})
    self.all({ :conditions => { :group => Group::CONDITION } }.merge(options))
  end

  def self.subcategories(options = {})
    self.all({ :conditions => { :group => Group::SUBCATEGORY } }.merge(options))
  end

  def self.non_brands(options = {})
    self.all({ :conditions => [ "`group` != ? AND `group` != ?", Tag::Group::SUBCATEGORY, Tag::Group::BRAND] }.merge(options))
  end
end

My goal is to use Formtastic to provide a grouped multiselect box, grouped by the column, "group" with the tags that are returned from the non_brands method. I have tried the following:

= f.input :tags, :required => false, :as => :select, :input_html => { :multiple => true }, :collection => tags, :selected => sel_tags, :group_by => :group, :prompt => false

But I receive the following error:

(undefined method `klass' for nil:NilClass)

Any ideas where I'm going wrong?

Thanks for looking :]

A: 

I'd first move your Group class out of this file, and just inherit from where you want, or use a Module in this class. This is the preferred way of getting methods an constants into a class and staying organized.

Joseph Silvashy
A: 

I'm not sure we support :group_by with a custom :collection. In fact, that who part of the code was a messy contribution. So, try omitting the :collection for starters, and see where you end up. If there's a bug with Formtastic, please add an issue on Github.

Justin French