Rails在具有额外字段的表格上将Has_Many插入Has_Many

时间:2018-09-04 00:03:56

标签: ruby-on-rails ruby activerecord

我们有一个简单的应用程序,我们创建了以下模型:

class Cliente < ApplicationRecord
    has_and_belongs_to_many :hardware
end

class Hardware < ApplicationRecord
    has_and_belongs_to_many :clientes
end

我们创建了一个中间表“ clientes_hardwares”,当我们为客户端分配硬件时,我们想在表“ vigencia”上设置另一个字段,表:

enter image description here

在我们的控制器上设置:

def sethardware
    @cliente = Cliente.find(params[:cliente_id])
    @cliente.hardware << Hardware.find(params[:hardware_id])

    @cliente.hardware.build(:vigencia => "2018-01-01")
    if @cliente.save
        flash[:info] = 'Cliente creado correctamente'
        redirect_to action: 'show', id: params[:cliente_id]
    else
        flash[:alert] = 'Error al crear el usuario'
        redirect_to action: 'show', id: params[:cliente_id]
    end
end

无此行:

@cliente.hardware.build(:vigencia => "2018-01-01")

它可以正常工作并设置client_id和hardware_id,我们如何设置称为“ vigencia”的额外字段,因为如果调用like build和like param,则表明硬件没有该属性?

致谢

1 个答案:

答案 0 :(得分:1)

如果需要将属性添加到联接表(clientes_hardwares),<<方法(不显式使用联接表)将不起作用,因为它不会设置任何其他属性(请注意,这些附加属性不在客户端或硬件,但在连接表中)。您必须改为定义并使用联接模型:

class Cliente < ApplicationRecord
  has_many :clientes_hardwares
  has_many :hardwares through: :clientes_hardwares
end

class Hardware < ApplicationRecord
  has_many :clientes_hardwares
  has_many :clientes through: :clientes_hardwares
end

class ClientesHardware < ApplicationRecord
  belongs to :cliente
  belongs to :hardware
end

def sethardware
  @cliente = Cliente.find(params[:cliente_id])
  @hardware = Hardware.find(params[:hardware_id])

  @cliente.clientes_hardwares.build(
    :hardware => @hardware, 
    :vigencia => "2018-01-01"
  )
  if @cliente.save
    flash[:info] = 'Cliente creado correctamente'
    redirect_to action: 'show', id: params[:cliente_id]
  else
    flash[:alert] = 'Error al crear el usuario'
    redirect_to action: 'show', id: params[:cliente_id]
  end
end