unable to access model related with has_one
-
03-07-2019 - |
Question
I have two models: Show
and Venue
. Show has one venue while each venue belongs to show. This condition is defined in both model files with has_one
& belongs_to
statements properly. However, I'm not able to access the venue by doing show.venue
. Consider the following code where s is a Show
instance:
logger.info("*********************")
logger.info("#{s.inspect}")
logger.info("#{Venue.find(s.venue_id)}") # Works
logger.info("#{s.venue}") # Causes a MySQL Error
logger.info("*********************")
I feel like the line that causes the MySQL error should work. This is the error:
ActiveRecord::StatementInvalid (Mysql::Error: Unknown column 'venues.show_id' in 'where clause': SELECT * FROM `venues` WHERE (`venues`.show_id = 95) LIMIT 1)
I have no idea why it is trying to access venues.show_id
. Any ideas?
Solution
You have the foreign keys reversed. In ActiveRecord's conventions, the class with the belongs_to should map to the database table with the foreign key. See the ActiveRecord API: "The belongs_to association is always used in the model that has the foreign key." This makes some sense, if you think about the way that belongs_to interacts with both has_one and has_many (as you obviously can't put the foreign keys in the has_many model).