我正在尝试链接位置和操作表,以便我可以在操作视图中的位置表中显示一些数据。但是,我被困住了,不知道该怎么办。任何帮助,将不胜感激。
#below are models#
class Location < ApplicationRecord
has_many :operatings
end
class Operating < ApplicationRecord
belongs_to :location
end
##below are my tables##
enable_extension "plpgsql"
create_table "locations", force: :cascade do |t|
t.string "country"
t.string "supra_region"
t.string "region"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "operatings", force: :cascade do |t|
t.string "operating_company_name"
t.string "address"
t.date "year_formed"
t.string "other_operational_countries"
t.string "about_company"
t.string "current_focus"
t.string "incumbent_irm_contractor"
t.string "irm_frame_agreements"
t.text "estimated_irm_budgets"
t.integer "location_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["location_id"], name: "index_operatings_on_location_id", using: :btree
end
add_foreign_key "operatings", "locations"
###below is my operating controller###
def create
@operating = Operating.new(op_company)
if @operating.save
flash[:success] = "A recorded has been successfully Saved"
redirect_to operatings_path
else
render 'new'
end
end
####routes####
resources :offshores, :index, :show, :new, :create, :destroy
resources :locations, :index, :show, :new, :create, :destroy
答案 0 :(得分:1)
由于Location
和Operating
模型使用has_many
和belongs_to
链接在一起,如果模板中有operating
个对象,则很容易访问其位置的属性:
<% @operatings.each do |operating| %>
<div>The name of its location: <%= operating.location.name %></div>
<% end %>
你需要小心这一点。如果仅从数据库中获取操作,则访问该location
循环中的每个操作的each
属性将触发针对每个操作项的单独数据库查询。这称为 N + 1 查询,效率非常低。要解决此问题,请确保在使用includes
加载操作时预取相关位置:
# in the controller
@operatings = Operating.all.includes(:location)
这样,每次操作的相关位置将仅使用一个查询获取。