[英]Rails Insert Has_Many to Has_Many on table with extra field
我們有一個簡單的應用程序,我們創建了以下模型:
class Cliente < ApplicationRecord
has_and_belongs_to_many :hardware
end
和
class Hardware < ApplicationRecord
has_and_belongs_to_many :clientes
end
我們創建了一個中間表“ clientes_hardwares”,當我們為客戶端分配硬件時,我們想在表“ vigencia”上設置另一個字段,即表:
在我們的控制器上,我們設置:
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”的額外字段,因為如果我們像build和like param這樣調用,則表明硬件沒有該屬性?
問候
如果您需要向聯接表(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.