Changing primary key

I have changed the primary key on a table “statuses” to now be
entity_id

In my status model I have:

self.primary_key = ‘entity_id’

when I try to render a collection of comments associated with a status
like so:

<%= render @comments %>

I get this error:

PG::UndefinedColumn: ERROR: column comments.status_id does not exist
LINE 1: SELECT “comments”.* FROM “comments” WHERE “comments”.“status_id”

I’m assuming when the above call is constructed by rails it is assuming
the table statuses has primary key status.id by convention…

so – is it no longer possible to use the render functionality as above?
Or have I missed something which I need to make this work?

How can I get rails to use entity_id instead of the now changed
status_id?

Hi

On Thu, May 19, 2016, at 19:21, Johnny S. wrote:

<%= render @comments %>

I get this error:

PG::UndefinedColumn: ERROR: column comments.status_id does not exist
LINE 1: SELECT “comments”.* FROM “comments” WHERE “comments”.“status_id”

I’m assuming when the above call is constructed by rails it is assuming
the table statuses has primary key status.id by convention…

All it does is taking the model name and suffix it with _id. Specifying
:foreign_key option should work.

:foreign_key
Specify the foreign key used for the association. By default this is
guessed to be the name of this class in lower-case and “_id”
suffixed. So a Person class that makes a has_and_belongs_to_many
association to Project will use “person_id” as the default
:foreign_key.

Hmmm…

OK, I have put this in place:

class Comment < ApplicationRecord
belongs_to :user
belongs_to :published_entity, foreign_key: “entity_id”

but rails is still trying to use status_id…

(I have a class PublishedEntity which status inherits from)

class Status < PublishedEntity
self.table_name = ‘statuses’
self.primary_key = ‘entity_id’

maybe this is causing problems?

Hi Fred,

@comments is a collection of comments on a status

Johnny

On Thursday, May 19, 2016 at 11:21:50 AM UTC+1, Ruby-Forum.com User
wrote:

What exactly is @comments?

Fred

Hi,

On Thu, May 19, 2016, at 20:10, Johnny S. wrote:

Hi Fred,

@comments is a collection of comments on a status

If it’s called from status (model?) using has_many, you need to define
foreign key in it.

Thanks Nanaya,

looks like that will do the trick!

Johnny