【问题标题】:Table associations in Rails - ActiveRecordRails 中的表关联 - ActiveRecord
【发布时间】:2021-11-30 10:40:51
【问题描述】:

有没有办法从rails console 获取表关联?我想直接从控制台检查与特定表的关系,而不是连接到数据库。

【问题讨论】:

  • 不清楚你想做什么。 get a table associationcheck the data related to the specific table 是什么意思?
  • 为了更好的解释,我想从控制台获取特定表的关联(关系)输出。也就是说,看看和其他表有没有关系。

标签: ruby-on-rails rails-activerecord


【解决方案1】:

假设您在 DB 中有 UserPost 模型以及相应的表 usersposts。用户has_many :posts 关联已定义,那么你可以这样做:

$ rails console
u = User.all.first # or 
User.last # or 
User.find(1)
u.posts # or
u.posts.first # or
u.posts.where(...)

如果你有种子数据

【讨论】:

  • 这仅提供属于关系的数据,我尝试查看关系本身。编辑了问题。
猜你喜欢
  • 1970-01-01
  • 2010-10-06
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多