gpt4 book ai didi

ruby-on-rails - 事件记录错误 : Couldn't find Customer with 'id' =1 [WHERE (`customers` .`company_id` IS NOT NULL) AND `customers` .`company_id` = ?] RUBY ON RAILS

转载 作者:行者123 更新时间:2023-11-28 20:54:39 25 4
gpt4 key购买 nike

我正在我的 Ruby on Rails Controller 上运行 RSPEC 测试,这是我正在测试的 Controller 操作:

Controller 代码:

class Customers::AccountsController < ApplicationController
before_action :set_customer

def index
@accounts = @customer.accounts
respond_to do |format|
format.html
format.json
end
end

def set_customer
@customer = current_member.company.customers.find(params[:customer_id])
end
end

这是我的 RSPEC 测试代码:

before do
@member = FactoryGirl.create(:member)
@company = FactoryGirl.create(:company, owner_id: @member.id)
@customer = FactoryGirl.create(:customer_john_human,company_id:@company.id)
end

describe "GET INDEX" do
it "gets the index html page" do
get :index, {:customer_id=>@customer.id, :format=>:json}
end
end

错误:

ActiveRecord::RecordNotFound:
Couldn't find Customer with 'id'=1 [WHERE (`customers`.`company_id` IS NOT NULL) AND `customers`.`company_id` = ?]
# ./app/controllers/customers/accounts_controller.rb:87:in `set_customer'
# ./spec/support/engine_controller.rb:25:in `process_action'
# ./spec/support/engine_controller.rb:3:in `get'
# ./spec/controllers/customers/accounts_controller_spec.rb:21:in `block (3 levels) in <top (required)>'

我不确定 customer.company_id = ? 是什么意思,- 如果我这样做:

puts @customer.inspect

我得到以下输出:

#<Customer id: 2, user_id: nil, title: nil, first_name: "John", last_name: "Kusu", created_at: "2015-04-27 18:42:00", updated_at: "2015-04-27 18:42:00", deleted_at: nil, company_name: nil, company_id: 6>

据我所知,company_id 已定义并设置为 6。我不确定为什么会收到此错误?

最佳答案

您正在引用未正确设置的一对多关系。

  def set_customer
@customer = current_member.company.customers.find(params[:customer_id])
end

此代码声明 current_member 属于一家拥有许多客户的公司。在属于该公司的客户中,返回具有此 ID 的客户。

要实现这一点,您的客户表需要有一个名为 company_id 的外键。查看您的数据库迁移和 this Rails guide .

同时将 belongs_to 添加到您的 Customer 类(首先执行此操作!然后测试。这可能就是您所需要的。)

class Customers::AccountsController < ApplicationController
before_action :set_customer
belongs_to :company

关于ruby-on-rails - 事件记录错误 : Couldn't find Customer with 'id' =1 [WHERE (`customers` .`company_id` IS NOT NULL) AND `customers` .`company_id` = ?] RUBY ON RAILS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com