我已经接近大学项目的最后期限了(3周),我遇到了几个问题。这是一门专题课程,我不能总是提到我的导师。
早些时候,我问了一个问题,为一个没有外键的表提供了解决方案,多亏了这个网站上的善良的人,这个问题终于解决了。一个长期存在的问题是如何让表使用外键,其中一个表将永远不会在索引中显示一个数据记录。
这是“托运”表控制器的创建方法,在该方法中,我尝试创建一个与“快递员”的关联,该“快递”是托运belongs_to和has_many的。以下几行是我课程的文档说明:
@cour_id=params[:shipment][:courier_id]
@courier=Courier.find(@cour_id)
@shipment=Shipment.new(params.require(:shipment).permit(:tracking_number, :shipment_date))
@shipment.courier<< @courier
@shipment.save
redirect_to shipment_path(@shipment)
@shipment=Shipment.new(shipment_new_path)
if @shipment.save
redirect_to(:controller=>'shipment' ,:action=>'index')
else
render('new')
end
end
关联似乎是必要的,因为托运/new.erb.html上的表单之一是从它的一个表列中删除一组Courier记录。显示在该页面中的表单中。
我遇到的问题是在“@shipment.courier << @NilClass”一行中,“<<”被视为nil:NilClass的一个未定义的方法。我尝试过这行代码的变体(@shipment.couriers.,@shipment.courier.id.),但这似乎没有什么区别。
我怀疑,一个更紧迫的问题是在这个特定的表中发挥作用,我注意到,即使从后端,表似乎不会保存新的记录。尽管与其他表格相比没有什么特别的区别。我最初将它不能传递数据归因于表关联之间的不对齐,现在我将它解释为一个问题,即如果不适当地连接到Courier表的id,就无法正常工作。
问题是,我如何使这些协会发挥作用?
发布于 2020-12-21 18:20:28
这实际上只是您正在描述的一个标准运行的嵌套资源。我真的不知道如何处理问题中的代码混乱--但是Rails这样做的方法是:
resources :couriers do
resources :shipments,
only: [:index, :new, :create]
end
class ShipmentsController < ApplicationController
# use callbacks to avoid repitition
before_action :set_courier, only: [:new, :create, :index]
# GET /couriers/1/shipments
def index
@shipments = @courier.shipments
end
# GET /couriers/1/shipments/new
def new
@shipment = @courier.shipments.new
end
# POST /couriers/1/shipments
def create
@shipment = @courier.shipments.new(shipment_params)
if @shipment.save
# shorthand for courier_shipments_path(@courier)
redirect_to([@courier, :shipments])
else
render(:new)
end
end
private
# use a private method instead of repeating yourself
def shipment_params
params.require(:shipment)
.permit(:tracking_number, :shipment_date)
end
def set_courier
@courier = Courier.find(params[:courier_id])
end
end
# app/views/shipments/new.html.erb
<%= form_with(model: [@courier, @shipment]) do |f| %>
<div class="field">
<%= f.label :tracking_number %>
<%= f.text_field :tracking_number %>
</div>
<div class="field">
<%= f.label :delivery_date %>
<%= f.date_field :delivery_date %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
https://stackoverflow.com/questions/65389172
复制相似问题