-1

I'm trying to display the status of a model Pack based on a model Status.

The number of possible statuses is small, while there are many packs and each has a status.

I expect the status table will also be referenced by other models at a later stage.

I've added this to routes:

resources :packs do
   resources :statuses
end

And added a:

has_one :status

to packs.rb.

When I try to call the following from the view:

<%= pack.status.status %>

I get the following controller error:

PG::UndefinedColumn: ERROR: column statuses.pack_id does not exist

Clearly, I don't have this set up right, but I don't want statuses to reference packs.

How do I remove this association?

I tried using:

statuses.rb:

has_many :battery_packs

But then I removed it, and the error persisted.

So it may be that I need to roll-back a migration or something, but I'm not sure how to check.

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
graial
  • 79
  • 8
  • Does `pack` have `status_id`? – jvillian Aug 21 '18 at 17:13
  • no, looks like i made typo, the column is status only – graial Aug 21 '18 at 17:19
  • If `pack` is intended to hold a foreign key to `status`, then `pack belongs_to :status`. – jvillian Aug 21 '18 at 17:22
  • If you want have the status as model, then you will need set the associations as well. If you don't want this approach, then I suggest to make status as a column in packs and use enums in model – Pavan Aug 21 '18 at 17:25
  • Does has_one also use the foreign key? has_one felt more appropriate to this situation though I'm still trying to evaluate the similarity to this question: https://stackoverflow.com/questions/19409912/rails-association-with-models-and-migration – graial Aug 21 '18 at 17:31
  • You should really take a look at the [has_one Association docs](https://guides.rubyonrails.org/association_basics.html#the-has-one-association). It's quite clear. `has_one` implies the foreign key is on the other (i.e., `status`) model, which is not what you say you want. – jvillian Aug 21 '18 at 17:33
  • That was the doc that I was reading. Though admittedly it's still not that clear to me (implicitly or otherwise). However, belongs_to seems to be the preferred choice (and it is now working for me). So I will go with that. Thank you for your help – graial Aug 21 '18 at 17:57
  • Yes, the semantics can be a little non-intuitive. Added as an answer. Feel free to upvote/accept. – jvillian Aug 21 '18 at 18:12

1 Answers1

0

Given that your foreign key for status is on pack, you want:

class Pack < ApplicationRecord
  belongs_to :status 
end

As mentioned in comments and stated in the docs, has_one implies that status would have a foreign key for pack, which is not what you want.

jvillian
  • 19,953
  • 5
  • 31
  • 44