1

我有一个Member具有新创建形式的模型。该表格允许用户为每个成员分配一个部门和职位。职位是相对于部门而言的。在应用程序的单独部分中,用户可以创建部门并创建/分配职位。我正在尝试为新成员页面创建一个 grouped_collection_select,但是我的职位没有显示,只是部门作为类别。我相信这是一个关联问题,其中职位与各自的部门没有关联。我的位置模型中有字符串department_id,但是我认为选择不能将其读取为父级。如果有人能指出我正确的方向,那就太棒了。

给出错误的行:(来自新成员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 %>

我的架构看起来像:

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

我的模特协会:

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
4

1 回答 1

0

每个模型的主键 ( id) 都是整数,但关联的外键在迁移中定义为字符串。( department_id, production_id)。当 Rails 尝试建立关联时,这可能会导致问题,例如,"1" == 1计算结果为false. 通过新迁移或编辑现有迁移并重置数据库将外键更改为整数。

您可以确认是否已修复与 rails 控制台的关联:

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

这将查询数据库中的第一部门的所有职位。如果它引发错误,则关联设置不正确。如果它返回位置集合,则关联有效。

于 2016-01-03T11:18:37.590 回答