0

I am working on a Rails 5 project and have a model called Upvote that is polymorphic and belongs to either an Event or Suggestion. I am trying to specifically grab upvotes that belong to one category or the other as well as the user id of whoever created the event/suggestion, but am struggling because of the polymorphism. There was a similar post on this a few years ago, but when I tried implementing the technique it didn't work. Specifically, I added this code to my Upvote model:

belongs_to :suggestion, -> { where(upvotes: {idea_type: 'Suggestion'}) }, foreign_key: "idea_id"

but when I try something like

Upvote.includes(:suggestion).last

in the console I get this error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "upvotes"
LINE 1: SELECT "suggestions".* FROM "suggestions" WHERE "upvotes"."i...

Can anyone please help? Thanks :)

Community
  • 1
  • 1
flaurida
  • 411
  • 1
  • 5
  • 9

1 Answers1

1

On Rails5, belongs_to has an required: true clause by default... So, it always checks if the counter parts exists... and there is no has_many :upvote relation on Suggestion...

To don't require the counter part, you can add the option optional: true to your belongs_to clause

belongs_to :suggestion, -> { where(upvotes: {idea_type: 'Suggestion'}) }, foreign_key: "idea_id", optional: true

OBS1

I started a Pull Request on Rails recently just because of this question, and on this discussion we figured out that actually if you don't want that a belongs_to would be required: true by default, you can just config that behaviour setting the config:

Rails.application.config.active_record.belongs_to_required_by_default = false

That on fresh installs of Rails5 is set to true, but is not set for apps that where migrated to Rails5

cefigueiredo
  • 738
  • 3
  • 12
  • Thanks - is it OK to add the has_many on the polymorphic module itself? That is not my error I don't think unless this line has to be on on Suggestion rather than the Upvotable module that is included in Suggestion `has_many :upvotes, as: :idea, dependent: :destroy` – flaurida Feb 27 '17 at 23:57
  • Only if you scope it for the `idea_type == 'Suggestion'` but you still need the belongs_to scoped... or the upvote will raise errors when trying save upvotes for type Event – cefigueiredo Feb 28 '17 at 03:32