无法访问与has_one相关的模型

时间:2022-10-03 23:30:58

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:

我有两个模特:Show和Venue。 Show有一个场地,每个场地都属于show。在具有has_one和belongs_to语句的两个模型文件中正确定义了此条件。但是,我无法通过show.venue访问该场地。请考虑以下代码,其中s是Show实例:

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:

我觉得导致MySQL错误的行应该有效。这是错误:

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?

我不知道为什么它试图访问venues.show_id。有任何想法吗?

1 个解决方案

#1


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

你有外键反转。在ActiveRecord的约定中,带有belongs_to的类应该使用外键映射到数据库表。请参阅ActiveRecord API:“belongs_to关联始终在具有外键的模型中使用。”如果您考虑belongs_to与has_one和has_many交互的方式(因为您显然无法将外键放在has_many模型中),这是有道理的。

#1


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

你有外键反转。在ActiveRecord的约定中,带有belongs_to的类应该使用外键映射到数据库表。请参阅ActiveRecord API:“belongs_to关联始终在具有外键的模型中使用。”如果您考虑belongs_to与has_one和has_many交互的方式(因为您显然无法将外键放在has_many模型中),这是有道理的。