Rails 5.1
fw_export.rb Modell rollen:Modell nicht auf DB speichern und zurück
class FwExport < ApplicationRecord
include Shared
has_one :location
end
location.rb Modell:
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
Lage Migrationsdatei:
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
der Konsole, wenn ich versuche, die folgendes zu tun:
location_record = Location.new(
:fw_exports_id => "fwexport.1510768198.5364478"
)
location_record.save
Es versagt und Rollback:
[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
Wenn ich tun:
Location.create!(fw_exports_id: "fwexport.1510768198.5364478")
Ich bekomme:
ActiveRecord::RecordInvalid: Validation failed: Fw export must exist
Irgendeine Idee, was das Problem sein könnte?
Lösung:
Ort gehört FwExport, so dass die Fremdschlüssel Bedürfnisse Singular wie in fw_export_id sein, nicht fw_exports_id
Es funktionierte, als ich diese chanve gemacht
In der Konsole, tun Sie Ihre 'location_record = Location.new (...)'. Dann 'location_record.valid?' (Es wird wahrscheinlich false zurückgegeben). Dann "location_record.errors.full_messages". – jvillian
Überprüfen Sie die Ausgabe von 'location_record.valid?' Und 'location_record.errors'? Das gibt dir vielleicht einen Hinweis darauf, was falsch ist. Sie könnten auch 'save!' Verwenden, um eine aussagekräftigere Fehlermeldung zu erhalten. –
ArgumentError: Falsche Anzahl von Argumenten (0 gegeben, erwartet 2) – EastsideDeveloper