无法访问与 has_one 相关的模型

发布于 2024-07-17 21:03:12 字数 738 浏览 2 评论 0原文

我有两个模型:ShowVenue。 演出有一个场地,每个场地都属于演出。 此条件在两个模型文件中均使用 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("*********************")

我觉得导致 MySQL 错误的行应该起作用。 这就是错误:

ActiveRecord::StatementInvalid (Mysql::Error: Unknown column 'venues.show_id' in 'where clause': SELECT * FROM `venues` WHERE (`venues`.show_id = 95)  LIMIT 1)

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2024-07-24 21:03:12

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文