-2

I have the following situation:

A model called State with some info:

pry(main)> State.last
 id: 35,
 region_id: 6,
 name: "São Paulo",
 abbreviation: "SP",
 created_at: Mon, 03 Jul 2017 09:38:22 -03 -03:00,
 updated_at: Mon, 03 Jul 2017 09:38:22 -03 -03:00,
 deleted_at: nil>

I want to know which Cities or another models and objects, is using this determined id.

This is the schema.rb to Cities

  create_table "cities", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.integer  "state_id",   null: false
    t.string   "name",       null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.datetime "deleted_at"
    t.index ["deleted_at"], name: "index_cities_on_deleted_at", using: :btree
    t.index ["state_id"], name: "index_cities_on_state_id", using: :btree
  end

Obs: "I tried to find some answer related to this topic, but I didn't found", If exists, please, report me and I will delete this question.

Thanks a lot

Diego
  • 11
  • 1
  • 1
  • 6

1 Answers1

1

First, you need to define the relationship between City and State.

# app/models/city.rb

class City < ApplicationRecord
  belongs_to :state
end
# app/models/state.rb

class State < ApplicationRecord
  has_many :cities
end

Now in the console you can call:

State.last.cities
alexalth
  • 93
  • 8