簡體   English   中英

如何在ActiveRecord :: Result上調用關聯

[英]How can I call associations on ActiveRecord::Result

我有兩個模型CityState 以下是城市與州之間的關聯。

state.rb

has_many :cities

city.rb

belongs_to :state

我執行以下查詢,

connection = ActiveRecord::Base.connection
query = "select * from states"
@states = connection.exec_query(query);

現在我要遍歷

@states.each do |s|
  s.cities # gives me an error because it is not an state object
end 

我想要這樣

state = State.last

cities = state.cities

如何在使用循環遍歷@states同時執行此操作?

您將需要使用ActiveRecord關聯,如下所示:

State.all.each { |state| state.cities }

暫無
暫無

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

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