![](/img/trans.png)
[英]Rails 4 “where”-query with “has_many belongs_to”-relationship, searching with specific count
[英]Getting data from multiple tables in a belongs_to and has_many relationship in Rails
我是一個PHP程序員來到Rails,似乎無法想象這簡單的Active Record調用。 基本上,我有兩張桌子, exchanges
和markets
。 它們如下:
class Market < ActiveRecord::Base
attr_accessible :date_created, :exchange_id, :market_name, :market_year
belongs_to :exchange
end
class Exchange < ActiveRecord::Base
attr_accessible :date_created, :exchange_name, :exchange_type
has_many :markets
end
我想檢索所有Markets
,並在同一個電話中,檢索有關這些markets
所有exchange
信息。
在PHP中,這看起來像: "SELECT * FROM markets, exchanges WHERE markets.id>0"
我所能做的就是選擇所有市場,然后單獨查詢以查找有關每個市場的交易所信息:
market = Market.first
exchange = Exchange.where(:id => market.exchange_id)
必須有一個更簡單的方法。 這有意義嗎?
如果您想要所有市場,包括他們的交易所,那么:
@markets = Market.includes(:exchange)
如果您想要一個單一的交易所及其所有市場,那么:
@exchange = Exchange.includes(:markets).first
@markets = @exchange.markets
如果您需要手動傳入id,請執行以下操作:
@markets = Market.where("exchange_id = ?", put_id_here)
這里有一些關於Rails中的熱切加載關聯的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.