Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么在模型类上使用'joins'方法时会出现ActiveRecord::StatementInvalid错误?_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 为什么在模型类上使用'joins'方法时会出现ActiveRecord::StatementInvalid错误?

Ruby on rails 为什么在模型类上使用'joins'方法时会出现ActiveRecord::StatementInvalid错误?,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有一个简单的rails应用程序,具有以下模型和关联: # app/models/vendor.rb class Vendor < ActiveRecord::Base has_many :products end # app/models/product.rb class Product < ActiveRecord::Base belongs_to :vendor, foreign_key: :account_id has_many :taxes end # ap

我有一个简单的rails应用程序,具有以下模型和关联:

# app/models/vendor.rb
class Vendor < ActiveRecord::Base
  has_many :products
end

# app/models/product.rb
class Product < ActiveRecord::Base
  belongs_to :vendor, foreign_key: :account_id
  has_many :taxes
end

# app/models/tax.rb
class Tax
  belongs_to :product, foreign_key: :item_id
end

我在尝试
Product.joins(:taxes)
时也会遇到类似的错误。这是否与外键不是默认的
…\u id
有关?

因为产品表中指向供应商表的
外键应该是
供应商id
,按照惯例,Rails通过表为外键约束添加表名前缀,
join
使用该列

从U到Rails文档:

。。。默认情况下,这是 猜测为带有“\u id”后缀的关联的名称。那么 定义所属人员关联将使用的 “person\u id”作为默认值:外键。同样地,你属于 :favorite_person,class_name:“person”将使用 “最喜欢的人的id”

您可以做的是“告诉”Rails供应商表(供应商模型)中使用的外键是
account\u id
,而不是
Vendor\u id

尝试:

class Vendor < ApplicationRecord
  has_many :products, foreign_key: :account_id
  ...
end
class Vendor < ApplicationRecord
  has_many :products, foreign_key: :account_id
  ...
end
Vendor.joins('INNER JOIN products ON products.account_id = vendors.id')