[英]Simple relational query in Rails
假設我有以下表格:
product transaction
------------------ ------------------
| id | name | | id | product |
------------------ ------------------
| 1 | Product A | | 1 | 2 |
| 2 | Product B | | 2 | 3 |
| 3 | Product C | | 3 | 2 |
------------------ ------------------
現在,假設我要列出transaction
表,但我想顯示產品名稱而不是產品ID。
在原始SQL中,我將執行以下操作:
SELECT product.name FROM transaction, product WHERE transaction.product = product.id
我很難弄清楚如何使用Rails的Active Record查詢接口來完成此工作。 我相信這對您的Rails專家來說是微不足道的。
如果您想通過“鐵路方式”解決它:
首先:將交易中的列product
更改為product_id
,並且表名應為復數形式,否則必須在模型中添加例如set_table_name 'transaction'
,如果不進行更改,將會錯過很多Rails的期貨。
添加/更改這些模型:
class Product < ActiveRecord::Base
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :product
end
如果您堅持使用列名“ product”,則必須將belongs_to
更改為:
belongs_to :product, :foreign_key => 'product'
但這有點丑陋
最后,使用此:
Transaction.includes(:product)
或者如果您只想要那些擁有產品的人
Transaction.joins(:product)
注意:我記不清了,但是我認為在某些應用程序中使用“事務”作為表名存在問題。 也許其他人對此有所了解。
transaction.joins('LEFT OUTER JOIN product ON transaction.id = product.id')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.