简体   繁体   English

查询具有数组数据类型的Rails Postgres

[英]Query Rails Postgres with array data type

So, Ive been trying to query my PostgreSQL model in Rails, but get the following error: 因此,我一直试图在Rails中查询我的PostgreSQL模型,但得到以下错误:

undefined method `id' for TransactionTemplate::ActiveRecord_Relation 未定义的方法id为TransactionTemplate :: ActiveRecord_Relation

My code: 我的代码:

    @transaction_templates = TransactionTemplate.where("transaction_category_id = 1")
    @transaction = Transaction.where("transaction_template_id in (?)", @transaction_templates.id)

I know that the transaction templates is an array and that there is therefor not just one ID it needs to look up, but multiple of IDs, just as I want it. 我知道事务模板是一个数组,因此,不仅有一个它需要查找的ID,而且还有多个ID,就像我想要的那样。

Any suggestions? 有什么建议么?

Try this: 尝试这个:

@transaction_templates = TransactionTemplate.where("transaction_category_id = 1")
@transaction = Transaction.where("transaction_template_id in (?)", @transaction_templates.map(&:id))

If you need just ids then try: 如果您只需要ID,请尝试:

@transaction_template_ids = TransactionTemplate.where("transaction_category_id = 1").pluck(:id)
@transaction = Transaction.where("transaction_template_id in (?)", @transaction_template_ids)

Or you have proper associations then 否则您便拥有适当的关联

@transaction = Transaction.joins(:transaction_template).where("transaction_category_id = 1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM