ruby-on-rails - 使用连接从三个模型进行 Rails 查询
问题描述
我的 Rails 应用程序中有以下模型:
class Test
has_many :tests_profiles
has_many :class_profiles
class TestsProfile
belongs_to :class_profile
belongs_to :test
class ClassProfile
has_many :tests_profiles
我必须查询tests
属于特定ClassProfile
的 . 我现在的辅助函数是这样的:
def get_tests(class_profile)
return Test.joins(:tests_profiles).where(tests_profiles: {class_profile_id: class_profile.id})
在我的erb
文件中,我正在遍历这样的结果:
<% tests = get_tests(class_profile) %>
<% tests.each do |test| %>
<th><%= test.name %></th>
<% end %>
但这里的问题是我得到了所有测试名称,而不是唯一与该特定ClassProfile
. 我怎样才能纠正它,使它按我想要的方式运行?
解决方案
你可以has_many through
在这里使用:
class Test
has_many :tests_profiles
has_many :class_profiles, through: :tests_profiles
class TestsProfile
belongs_to :class_profile
belongs_to :test
class ClassProfile
has_many :tests_profiles
has_many :tests, through: :tests_profiles
并class_profile.tests.each do
在视图中使用
推荐阅读
- angular - Angular:无法通过路由器传递对象?
- python - requests.get 在某些 url 上崩溃
- asp.net-mvc - 由于请求正文过大,大文件上传到 ASP.NET Core 3.0 Web API 失败
- image - 如何在 Dialogflow 中为 Twilio 创建包含丰富消息的响应?
- rust - tokio TcpStream 上的并发读/写
- wso2 - WSO2 商店无法登录具有内部/订阅者权限的新用户
- c# - 如何让每个士兵根据士兵指数轮换?
- r - R - ggplot2 - 当 x 轴是因子变量时,如果 geom_errorbar 超出限制,则添加箭头
- flutter - 如何正确聚焦基于焦点节点的 hasFocus 值有条件地创建的文本字段?
- json - 如何使用正则表达式匹配文档的第一个左大括号