2016-03-23 45 views
1

我遇到问题追踪为什么我的更新方法没有得到所需的参数。我有一个类似的测试显示和有效载荷工作。在这种情况下,有问题的路线是发票/ invoice_id/trip/id。如果您可以帮助我发现错误,并就如何在将来很好地解决这类问题提出任何建议。更新方法的参数数量错误(1代表2)

这是更新方法。

def update 
    if @trip.update(@trip.trip_id, trip_params) 
    head :no_content 
    else 
    render json: [@invoice, @trip].errors, status: :unprocessable_entity 
    end 
end 

使用以下私有方法。

private 

    def set_trip 
    @trip = Trip.where(:invoice_id => params[:invoice_id], :trip_id => params[:id]) 
    end 

    def trip_params 
    params.require(:trip).permit(:trip_id, :depart_airport, :arrive_airport, :passenger_first_name, :passenger_last_name, :passenger_count, :departure_date, :merchant_id) 
    end 

    def load_invoice 
    @invoice = Invoice.find(params[:invoice_id]) 
    end 

end 

我的失败测试看起来像这样。

test "should update trip" do 
    put :update, invoice_id: @invoice.invoice_id, id: @trip, 
    trip: {arrive_airport: @trip.arrive_airport, 
    depart_airport: @trip.depart_airport, 
    departure_date: @trip.departure_date, 
    passenger_count: @trip.passenger_count, 
    passenger_first_name: @trip.passenger_first_name, 
    passenger_last_name: @trip.passenger_last_name} 
assert_response 204 
end 
+0

只是为了检查,2是1还是1的错误2?你正在做从数据库加载的记录的任何模拟/存根? –

回答

1

如果要调用set_tripbefore_action然后update()方法应该是这样的

def update 
    if @trip.update(trip_params) 
    head :no_content 
    else 
    render json: [@invoice, @trip].errors, status: :unprocessable_entity 
    end 
end 

update()是一个实例方法可以使用对象调用,您只需要通过trip_params进去,希望这有帮助!

+0

我有点不喜欢。为什么它要求我提供两个参数,我应该只能通过一个参数。这是我的测试问题吗? – CheeseFry

+0

令人困惑的是'@ trip'不是Trip的一个实例 - 它是一个关系,ActiveRecord :: Relation.update确实需要2个参数。 –

+0

@RSB感谢您的明确示例。我认为让代码看起来尽可能标准化,这对于将来需要维护的人来说确实很有帮助。 – CheeseFry

1

当方法调用正在传递错误数量的参数的另一个方法时,您可能会收到此错误消息。

1

update将hash作为其唯一的参数,但是您正在更新方法中传递两个参数(@ trip.trip_id,trip_params)。这就是为什么你得到“错误数量的参数(1为2)更新方法”错误消息。正如@RSB所说的,只需传入trip_params,Trip实例就会被更新。

0

RSB是对的钱。原来在这种情况下,我的问题是在数据库级别。该表没有主键,所以我在私有方法中使用了 @trip = Trip.where,这导致它返回可能的行数组而不是特定的行。我在数据库级别更改了一些主键并更新了私有方法。 VoilàRSB的代码工作!

相关问题