轨道选择列表问题



我有一个模型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

每个模型的主键(id)都是整数,但关联的外键在迁移中定义为字符串。(department_idproduction_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

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

最新更新