views:

424

answers:

1

I have a Show model that has_one :venue, which is accomplished with each show having a venue_id

And my Venue model belongs_to :show

However I am having a problem accessing 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?

Thanks!

+5  A: 

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

Greg Campbell
i guess i got a bit confused because i think like this:"If a show HAS a venue, then a show HAS a venue_id to reference that venue." But I have to start thinking "If a show BELONGS to a venue, it must the id of the venue it BELONGS to."
Tony