我在轨道上有两个模型,具有以下关联:
class Manufacturer
has_many :equipments
end
class Equipments
belongs_to :manufacturer
end
我有一个Equipments
显示页面,其中包含以下字段:
title,
category_id,
sub_category_id,
manufacturer_id
当我在设备show
页面
我正在尝试提供一个按钮,点按该按钮会根据manufacturer_id
上的equipment_id
获取该页面上的url
,并将其从{{1}的记录中删除表。
我知道如何从Manufacturer
Manufacturer
页面进行操作。它会像:
show
。
但是我怎么能从装备展示页面那样做呢?
答案 0 :(得分:1)
有很多方法可以实现这一目标。 “正确”的方式是在您的设备展示页面中设置一个链接,该链接向ManufacturersController#destroy
操作发出删除请求,并将@equipment.manufacturer_id
作为参数发送。像这样:
<%= link_to 'Delete Manufacturer', manufacturer_path(@equipment.manufacturer_id), method: :delete, data: {confirm: 'Some confirmation message'} %>
这会将manufacturer_id
作为参数id
发送。这也假设你的routes.rb
类似于:
resources :manufacturers
然后,在manufacturers_controller.rb
:
def destroy:
@manufacturer = Manufacturer.find(params[:id])
@manufacturer.destroy
redirect_to some_place, notice: 'Manufacturer successfully deleted'
end
另外,如果您只有equipment_id
并想要检索关联的Manufacturer
,则可以执行以下操作:
@manufacturer = Manufacturer.joins(:equipments).where(equipments: {id: params[:equipment_id]}).first
@manufacturer.destroy if @manufacturer.present?
答案 1 :(得分:0)
在设备展示页面:
<%= link_to 'Delete', delete_manufacturer_equipment_path(@equipment.id), method: :delete, data: { confirm: 'Are you sure?' } %>
在设备控制器中:
def delete_manufacturer
@manufacturer = Manufacturer.joins(:equipments).where(equipments: {id: params[:id]}).first
@manufacturer.destroy if @manufacturer.present?
redirect_to :back, notice: 'Manufacturer successfully deleted'
end
路线
resources :equipments do
member do
delete :delete_manufacturer
end
end