在rails 5中创建两个表之间的关系

时间:2017-07-06 12:20:53

标签: ruby-on-rails ruby

我正在尝试在rails中建立两个表之间的关系 我可以在两个表之间共享数据。但是,我不能 将数据输入到操作表中。任何帮助将受到高度赞赏。

#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 :(得分:0)

尝试

tf.tanh

belongs_to将检查是否存在关联,您可以通过打印操作错误来调试

class Operating < ApplicationRecord
    belongs_to :location, :optional => true
end