【问题标题】:Rails selection list issueRails 选择列表问题
【发布时间】:2016-01-03 00:30:29
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails forms grouped-collection-select


    【解决方案1】:

    每个模型的主键 (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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2011-08-25
      相关资源
      最近更新 更多