在rails

时间:2017-07-08 00:32:59

标签: ruby-on-rails postgresql

我正在尝试链接位置和操作表,以便我可以在操作视图中的位置表中显示一些数据。但是,我被困住了,不知道该怎么办。任何帮助,将不胜感激。

 #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

1 个答案:

答案 0 :(得分:1)

由于LocationOperating模型使用has_manybelongs_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)

这样,每次操作的相关位置将仅使用一个查询获取。