如何知道某个项目或对象是否正在使用 rails 中的模型
How to know if a some item or object is using a Model in rails
我有以下情况:
一个名为 State 的模型,包含一些信息:
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>
我想知道哪些城市或其他模型和对象正在使用这个确定的 ID。
这是schema.rb到城市
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",如果存在,请报告我,我将删除此问题。
非常感谢
首先,您需要定义 City 和 State 之间的关系。
# app/models/city.rb
class City < ApplicationRecord
belongs_to :state
end
# app/models/state.rb
class State < ApplicationRecord
has_many :cities
end
现在您可以在控制台中调用:
State.last.cities
我有以下情况:
一个名为 State 的模型,包含一些信息:
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>
我想知道哪些城市或其他模型和对象正在使用这个确定的 ID。
这是schema.rb到城市
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",如果存在,请报告我,我将删除此问题。
非常感谢
首先,您需要定义 City 和 State 之间的关系。
# app/models/city.rb
class City < ApplicationRecord
belongs_to :state
end
# app/models/state.rb
class State < ApplicationRecord
has_many :cities
end
现在您可以在控制台中调用:
State.last.cities