我有两个模型City
和State
。以下是城市与州之间的关联。
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
时如何使用它{1>}?
答案 0 :(得分:1)
您将要使用ActiveRecord关联,如下所示:
State.all.each { |state| state.cities }