has_and_belongs_to_many关系中的Rails显示属性

时间:2018-10-02 14:07:39

标签: ruby-on-rails

所以我有员工和地区。员工可能/可能不属于某个区域,就像区域可能/可能没有员工一样。

型号:

Employee
 has_and_belongs_to_many :region, optional: true
Region
 has_and_belongs_to_many :employees, optional: true

我有一个看起来像这样的联接表:

create_table "employees_regions", id: false, force: :cascade do |t|
 t.integer "employee_id"
 t.integer "region_id"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.index ["employee_id"], name: "index_employees_regions_on_employee_id"
 t.index ["region_id"], name: "index_employees_regions_on_region_id"
end

我的员工控制者:

class Admin::EmployeesController < Admin::ApplicationController
  belongs_to_app :employees
  add_breadcrumb 'Employees', :admin_employees_path
  before_action :load_employee, only: [:show, :edit, :update, :destroy]

  def index
    @employees = Employee.ordered.paginate(page: params[:page])
    @employees = @employees.search(params[:search]) if params[:search]
    respond_with @employees
  end

  def show
    respond_with @employee
  end

  def new
    @employee = Employee.new
    respond_with @employee
  end

  def create
    @employee = Employee.new(employee_params)
    flash[:notice] = 'Employee created successfully' if @employee.save
    respond_with @employee, location: admin_employees_path
  end

  def edit
    respond_with @employee
  end

  def update
    flash[:notice] = 'Employee updated successfully' if @employee.update_attributes(employee_params)
    respond_with @employee, location: admin_employees_path
  end

  def destroy
    flash[:notice] = 'Employee deleted successfully' if @employee.destroy
    respond_with @employee, location: admin_employees_path
  end

  private

  def load_employee
    @employee = Employee.find_by!(id: params[:id])
  end

  def employee_params
    params.require(:employee).permit(:first_name, :last_name, :title, :leadership, :bio, :avatar, :region, :region_id)
  end
end

然后在我看来:

.table-responsive
table.table.table-striped.table-hover
  thead
    tr
      th First Name
      th Last Name
      th Title
      th Avatar
      th Leadership
      th Region
      th &nbsp;
  tbody
    - @employees.each do |employee|
      tr
        td = employee.first_name
        td = employee.last_name
        td = employee.title
        td = image_tag employee.avatar
        td = employee.leadership
        td = employee.region.map(&:name).join(', ')

问题来了。对于区域,它什么也不显示。我尝试了以下操作:employee.region_id(显示正确的关联ID),employee.region(&:name)(显示Region :: ActiveRecord_Associations_CollectionProxy123),employee.region.name(显示Region)和employee.region&.name (显示Region)。

我要查看的是区域名称。因此,如果某个员工在东北工作,应该说是东北而不是地区。如何在员工视图中点击该区域的名称?

1 个答案:

答案 0 :(得分:0)

将模型更新为使用复数,然后将控制器的参数更新为:

 def employee_params
  params.require(:employee).permit(:first_name, :last_name, :title, :leadership, :bio, :avatar, :regions).tap do |employee|
  employee[:region_ids] = [employee[:regions].to_i]
  employee.delete(:regions)
 end
end