rails & postgreSQL - How can I update a data with existing primary key? - ruby-on-rails

I want to update some data in Lecture(id, name, etc.) table.
For example, there is a data(id: 1, name: "first") in the Lecture.
When I typed Lecture.create(id: 1, name: "newer") =>
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey"
Is there any way to update data?

Try this:
Lecture.find(1).update(name: "newer")
Find more information on update here: http://guides.rubyonrails.org/active_record_basics.html#update
The reason it didn't work is because the id is unique. When you were using create, it was trying to create a NEW record with id of 1, not edit the same record.

PG::UniqueViolation: ERROR: duplicate key value violates unique
constraint "lectures_pkey"
id is the default primary key which shouldn't be changed or duplicated. As you are inserting a row with an existing id, you get that error.
Instead, you need to do like below.
#lecture = Lecture.find(1)
#lecture.update_attributes(name: "newer")

You can use
lec = Lecture.find(1)
lec.update_attributes(name: "newer")
You are getting error PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "lectures_pkey" due to you can not create record with same id. Id is primary key in table.

All of the current answers are correct if you don't mind loading the record and then updating it. If you don't need to actually load the record, and just want to update data in the database you can do
Lecture.where(id: 1).update_all(name: "newer")
This will skip all validations, etc and just do a direct sql update of the data in the database of the record with id == 1

Related

using string as id

I am making a KMM app using SQLDelight for the cache and recently I changed my database entities to use Text(String) for the id field instead of Int, now i am getting an error when inserting, I might just be missing some sqlDelight knowledge
here is my table:
CREATE TABLE sidework_Entity(
id TEXT NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
employees TEXT NOT NULL,
todoToday INTEGER AS Boolean DEFAULT 0
);
here is my insert method:
insertSidework:
INSERT OR REPLACE
INTO sidework_Entity(
id,
name,
employees,
todoToday
) VALUES (?,?,?,?);
here is my error:
statement aborts at 5: [INSERT OR REPLACE
INTO sidework_Entity(
id,
name,
employees,
todoToday
) VALUES (?,?,?,?)] datatype mismatch
I think it is most likely the Primary Key i have set on the id field or something of that sort but the documentation is a bit short.
The solution to this problem is actually running a migration. Although deleting the app to clear the database cache is a valid solution for testing purposes. For an app in production, this isn't the correct approach.
Documentation for running Migration
Stackoverflow answer with explanation

Deleting Entity with Foreign Key Relationship Without Deleting Reference Object

My problem is with the generic "Delete" in the BidController I am getting the typical Error:
The DELETE statement conflicted with the REFERENCE constraint "fkw_....". The conflict occurred in database table ..., column ....
The statement has been terminated.
Thank you so much for any and all help.
Try updating the ActiveBidId with a null value and then delete the bids.That way you break the link between the Item and Bid and than you can remove the Data from Bids.
Try making the relationship as OPTIONAL. This way your items can have null Foreign Keys.
If you are using database first approach:
CREATE TABLE Item(
ItemId INT PRIMARY KEY,
ActiveBidId INT NULL FOREIGN KEY REFERENCES Bid(BidId)
// ...
);
If you already created the table, then you can alter your table as follows:
ALTER TABLE Item
DROP CONSTRAINT FK_ActiveBidConstraint -- The name of your constraint
GO
ALTER TABLE Item
ADD CONSTRAINT FK_ActiveBidConstraint FOREIGN KEY (ActiveBidId) -- The name of your constraint
REFERENCES Bid(BidId);
Apparently I am able to set the GUID to null, so I am posting a simple answer.
In my BidController I have updated my code:
item = null;
This removes the reference to the bid and so the bids are free to be removed!

How to handle an autoincremented ID in HANA from a SAPUI5-application?

in my SAPUI5-Application I got the following function that takes the data and creates an entry in my HANA DB:
onCreateNewCustomer: function(){
var oEntry = {};
oEntry.NAME = this.byId("name").getValue();
oEntry.CITY = this.byId("city").getValue();
oEntry.PHONE = this.byId("phone").getValue();
oEntry.ID = this.byId("id").getValue();
// Post data to the server
this.getOwnerComponent().getModel("CustomerModel").create("/Customer", oEntry, null);
this.byId("createCustomer").close();
//location.reload();
}
The creating process works and my entries get saved. In the next step I wanted to implement my table in HANA in that way, that the ID of the entries will be autoincremented so the user does not have to enter it. I used the following command to create my table:
create column table TABLE
(ID bigint not null primary key generated by default as IDENTITY,
FIRSTNAME nvarchar(30))
That worked, table is created. The problem now is, if I use the code above without providing the ID, the following error is logged by the console:
The following problem occurred: HTTP request failed 400,Bad Request,The serialized resource has an missing value for member 'ID'.
The entry does not get saved in my DB. If I execute the following SQL-Statements in my HANA Workbench without providing the ID, it works:
insert into TABLE (FIRSTNAME) values (‘David’);
insert into TABLE (FIRSTNAME) values (‘Mike’);
insert into TABLE (FIRSTNAME) values (‘Bobby’);
So I did some searching on google but did not find a proper solution on how to do this. My goal is that the entry gets saved and the ID is provided by my HANA DB without providing it from my SAPUI5 Application.
Probably you are using ODataV2 XSODATA implementation which does not support auto-increment. The possible solution here is to use a database sequence and then with a separate request get a value from it and use it in OData create statement.
Did you try creating a new record by commenting out the below code like ?
oEntry.ID = this.byId("id").getValue();
With identity fields, if you provide the value you have to explicitly identify that you are providing the column value. Otherwise, just omit the columnn name and value from the INSERT command.

Symfony - Try to update a record in DB with some foreign keys

Thanks a lot for recent help. It works really well, but now I am having some problems with this code.
//Save course record to DB
$record_course = new course();
$record_course->setName($courseInfo['name']);
$record_course->setUrl($courseInfo['url']);
$record_course->setAcronym($courseInfo['acronym']);
$record_course->setCourseTypeId($record_courseType->getId());
$record_course->setStartDate($courseInfo['startDate']);
$record_course->setCollegeId($record_college->getId());
$record_course->setPlanUrl($courseInfo['planUrl']);
$record_course->replace();
As you can see, I try to update a record but now we have some foreign keys. In this case is CourseTypeId and CollegeId. When i try to replace this record i get next message:
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (grabmark.course, CONSTRAINT course_course_type_id_course_type_id FOREIGN KEY (course_type_id) REFERENCES course_type (id))"
Anyone can help me please?
Sorry, but i am initiate now in symfony and it's my first contact with an MVC Framework.
Thanks a lot,
Alexandre Sousa
Alexandre, this is more of a database issue than symfony.
When you attempt to update this record, you are changing CourseTypeId and CollegeId with new values and these according to you are foreign keys. Are the values in these fields (CourseTypeId and CollegeId) present in the table where these keys are being referenced from?
For example:
Lets say you are setting CourseTypeId to 15 and CollegeId to 10, then are the values 15 and 10 also present in the database table from where these foreign keys are being referenced? If not, then the Integrity constraint error you are experiencing shows up. Since you are UPDATING and not really INSERTING, then the values 15 and 10 must be present in the table from where the two foreign key columns are referencing.
Does this help?

Rails: id field is nil when calling Model.new

I am a little confused about the auto-increment id field in rails. I have a rails project with a simple schema. When i check the development.sqlite3 I can see that all of my tables have an id field with auto increment.
CREATE TABLE "messages" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "text" text, "created_at" datetime, "updated_at" datetime);
But when I call Message.new in the console, the resulting object has an id of nil.
>> a = Message.new
=> #<Message id: nil, text: nil, created_at: nil, updated_at: nil>
Shouldn't the id come back populated?
No, that's the correct behavior. When you create an object via new (as in your example), Rails doesn't persist it to the database (just in memory).
If you do Message.create, or Message.save like theIV said, then the id will be populated.
Like fig said,
n = Movie.new
n.save
=> true
means that it is saved and will be given an ID. Alternatively,
n = Movie.create!
automatically saves and stores it in the database and gives it an ID with one line of code.
As far as I know, the id field only gets assigned on saves, not on news.
All answers above are correct. To add to them, calling the #save method on an instance will return true if it was able to insert into database and false if it wasn't successful. Using the ::create method will make a new instance of your model, and will call #save on it.
You can also use the #save! or ::create! methods. The difference is that these will raise an error (as opposed to returning boolean) if they were not successful in their insertion to the database.
In my case, I called Model.create(event_id) with constant value (6) that was NOT the event's actual id. There was no error, and an Active Record Model was returned with other attributes, except id was nil.
I fixed my bug after some hours of debugging by changing the value to the actual reference id of the existing Event.id (as it was previously). Note that you might get this error if you have SQL foreign constraint to some other table, but you are using incorrect id for the reference.

Resources