簡體   English   中英

Rails多對多模型查詢問題

[英]rails many to many model query problem

有兩個模型產品和禮物,這是關系

產品屬於很多禮物一個禮物類別有很多產品

所以他們有一個關聯表,名為gift_products

我怎么寫代碼來實現這個SQL

從gift_products中選擇前1個,其中product_id = 1和gift_id = 2

意思是我要檢查,是關聯表中已有的特定記錄,我是新手,

我嘗試使用

rails g model GiftProduct
GiftProduct.find_by_sql("select top 1 from gift_products where product_id=1 and gift_id=2")

生成一個模型來像往常一樣操作關聯表,但是似乎不起作用,我使用sqlite3作為dev db。

這是你想要的嗎?

GiftProduct.where(:product_id => 1, :gift_id => 1).first

如果沒有這樣的記錄,則返回nil ,否則返回gift_product記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM