Ruby on rails Rails:为什么会出现ActiveRecord错误;“表”的子句条目中缺少;?
我在Ruby(而不是Rails)应用程序中有两个模型:Ruby on rails Rails:为什么会出现ActiveRecord错误;“表”的子句条目中缺少;?,ruby-on-rails,ruby,postgresql,activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,我在Ruby(而不是Rails)应用程序中有两个模型:Bill和BillItem。我正在使用ActiveRecord尝试查找所有账单,这些账单的BillItem属性为1 bill.rb class Bill < ActiveRecord::Base has_many :bill_items end class BillItem < ActiveRecord::Base belongs_to :bill end 这两种情况都会导致错误: ActiveRecord::Stat
Bill
和BillItem
。我正在使用ActiveRecord尝试查找所有账单
,这些账单的BillItem
属性为1
bill.rb
class Bill < ActiveRecord::Base
has_many :bill_items
end
class BillItem < ActiveRecord::Base
belongs_to :bill
end
这两种情况都会导致错误:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry
for table 'bill_items'
LINE 1: SELECT "bills".* FROM "bills" WHERE "bill_items"."user_id" ...
^
: SELECT "bills".* FROM "bills" WHERE (bill_items.user_id = 34)
在这方面也有类似的问题,但大多数似乎是命名问题(指的是
bill\u项目
,而不是bill\u项目
)。我被难住了,这是怎么回事?如评论中所述,您需要加入到另一个表中:
Bill.joins(:bill_items).where('bill_items.user_id' => 1)
在使用Rails 6应用程序时,我也面临同样的挑战 我有一款
产品
,属于另一款名为Badge
的型号
产品型号
class Product < ApplicationRecord
belongs_to :badge
end
class Badge < ApplicationRecord
has_many :products
end
以下是我解决问题的方法:
class Home < ApplicationRecord
# This scope are from the Product model
scope :best_products, -> { best_sellers }
end
可以在活动记录关系中使用where
子句从多个表中检索筛选的数据
scope :best_sellers, -> { Product.joins(:badge).where('badges.name': 'Fair') }
scope :best_sellers, -> { Product.joins(:badge).find_by('badges.name': 'Fair') }
或
您可以在活动记录关系中使用find_by
子句从多个表中检索特定数据
scope :best_sellers, -> { Product.joins(:badge).where('badges.name': 'Fair') }
scope :best_sellers, -> { Product.joins(:badge).find_by('badges.name': 'Fair') }
注意:
class Home < ApplicationRecord
# This scope are from the Product model
scope :best_products, -> { best_sellers }
end
find_by
将只获取第一条记录,而忽略其他记录。默认情况下,它在查询中实现限制1
Fair
和Fair
是完全不同的字母/值/输入,因此请确保仔细检查您的值字母/值/输入,以避免调试时不必要的时间浪费
Home
,而不是以这种方式复制:
class Home < ApplicationRecord
scope :best_sellers, -> { Product.joins(:badge).where('badges.name': 'Fair') }
end
class Home{Product.joins(:badge.where('badges.name':'Fair')}
结束
您可以简单地使用此概念使其干燥:
class Home < ApplicationRecord
# This scope are from the Product model
scope :best_products, -> { best_sellers }
end
class Home{畅销书}
结束
这有助于避免代码重复,以便只在一个地方进行代码更改
您可以阅读Rails文档
就这些
我希望这有帮助您需要加入
账单项目
,然后才能引用它。账单项目或账单中是否有用户id字段?