模型不保存到DB并回滚

时间:2017-11-15 18:33:55

标签: ruby-on-rails activerecord

Rails 5.1

fw_export.rb模型:

class FwExport < ApplicationRecord
  include Shared

  has_one :location

end

location.rb模型:

class Location < ApplicationRecord
  include Shared

  belongs_to :fw_export

end

locations_controller.rb:

class LocationsController < ApplicationController
  before_action :set_location, only: [:show, :edit, :update, :destroy]

  def new
    @location = Location.new
  end

  def create
    @location = Location.new(location_params)

    respond_to do |format|
      if @location.save
        format.html { redirect_to @location, notice: 'Location was successfully created.' }
        format.json { render :show, status: :created, location: @location }
      else
        format.html { render :new }
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end


  private
    def set_location
      @location = Location.find(params[:id])
    end

    def location_params
      params.require(:location).permit(:fw_exports_id, :city, :state, :country, :api_source)
    end
end

位置迁移文件:

class CreateLocations < ActiveRecord::Migration[5.1]
  def change
    create_table :locations, id: :string do |t|
      t.string :fw_exports_id
      t.string :city
      t.string :state
      t.string :country
      t.string :api_source
      t.timestamps
      t.index [:fw_exports_id], unique: true
    end
  end
end

从控制台,如果我尝试执行以下操作:

location_record = Location.new(
  :fw_exports_id => "fwexport.1510768198.5364478"
)
location_record.save

失败并回滚:

[9] pry(main)> location_record = Location.new(
[9] pry(main)*   :fw_exports_id => "fwexport.1510768198.5364478"
[9] pry(main)* )
=> #<Location:0x0000000003e68888 id: nil, fw_exports_id: "fwexport.1510768198.5364478", city: nil, state: nil, country: nil, api_source: nil, created_at: nil, updated_at: nil>
[10] pry(main)> location_record.save
   (0.2ms)  BEGIN
   (0.1ms)  ROLLBACK
=> false

如果我这样做:

Location.create!(fw_exports_id: "fwexport.1510768198.5364478")

我明白了:

ActiveRecord::RecordInvalid: Validation failed: Fw export must exist

知道问题可能是什么?

解决方案:

位置属于FwExport,因此外键需要像fw_export_id一样是单数,而不是fw_exports_id

当我制作那个时,它起作用了

1 个答案:

答案 0 :(得分:0)

尝试致电location_record.errors.full_messages 紧接着:

location_record = Location.new(:fw_exports_id =>"fwexport.1510768198.5364478")
location_record.save

将输出复制到此处

它可能包含问题的原因