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

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..

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.

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

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?

What exactly is @comments?

Fred

Hi Fred,

@comments is a collection of comments on a status

Johnny

Hi,

Thanks Nanaya,

looks like that will do the trick!

Johnny

OK, next problem..

When I create a comment (from a form on the status page) the params hash
contains a parameter called:
status_entity_id
What I want is just:
entity_id

Processing by CommentsController#create as JS
  Parameters: {"utf8"=>"✓", "comment"=>{"content"=>"testing123"},
"commit"=>"Add Comment", "status_entity_id"=>"13"}

I assume rails is prepending the name of the controller to the id? Is
there a way to override this?