1

I have a model Member that has a new creation form. The form allows users to assign a department and position for each member to be a part of. The positions are relative to the department. In a separate part of the app, users can create departments and create/assign positions. I am trying to create a grouped_collection_select for the new members page, however my positions are not showing up, just departments as categories. I believe this is an association issue, where the positions are not being associated with their respective dept. I have the string department_id in my positions model, however I don't think the selection is able to read that as the parent. If anyone can point me in the correct direction that'd be awesome.

The line giving an error: (from the new members form_for)

<%= f.grouped_collection_select :title, Department.where(production_id: current_user.default_working_production_id).order(:department), :positions, :department, :id, :position, include_blank: true %>

My schema looks like:

create_table "departments", force: true do |t|
    t.string   "department"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "production_id"
end

create_table "positions", force: true do |t|
    t.string   "position"
    t.string   "department_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "production_id"
end

My model associations:

class Member < ActiveRecord::Base
    belongs_to :company
    validates :firstname, presence: true
    validates :email, presence: true
    def name
        "#{firstname} #{lastname}"
    end
end

class Department < ActiveRecord::Base
    has_many :positions
    attr_accessible :department
    validates :department, presence: true
end

class Position < ActiveRecord::Base
    belongs_to :department
    attr_accessible :department_id, :position, :department
end
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Dan Brookwell
  • 341
  • 2
  • 12

1 Answers1

0

The primary keys (id) of each Model are integers, but the foreign keys for the associations are defined in your migrations as strings. (department_id, production_id). This may be causing problems when Rails tries to make the associations because for example, "1" == 1 evaluates to false. Change the foreign keys to integers via a new migration or by editing the existing migration and resetting the db.

You can confirm if you've fixed the association with the rails console:

$> rails console
Running via Spring preloader in process 20933
Loading development environment (Rails 4.2.5)
irb(main):001:0> Department.first.positions

This will query the First department in the db for all of its positions. If it throws an error then the association is not setup properly. If it returns a collection of positions, the association works.

Jess
  • 428
  • 2
  • 9