如何在ActiveRecord :: Result上调用关联

时间:2019-02-13 05:44:43

标签: ruby-on-rails ruby-on-rails-5 rails-activerecord

我有两个模型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时如何使用它{}?

1 个答案:

答案 0 :(得分:1)

您将要使用ActiveRecord关联,如下所示:

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