rails 连接模块名称 [英] rails joins with module name

查看:33
本文介绍了rails 连接模块名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是如何加入两个模型

Here is how to join two models

User.where(:id => 1).joins(:posts)

但是如何使用模块/纳米空间连接两个模型

but how to join two models with module/namspace

@schedules= Swimming::Classschedule.joins(:Swimming::Slot).where(:date => @date)

似乎工作不正常(有错误信息)

seems not working properly (with error message)

:Swimming is not a class/module

更新

我已经更新到@schedules= Swimming::Classschedule.joins(:swimming_slots).where(:date => @date)

I have updated to @schedules= Swimming::Classschedule.joins(:swimming_slots).where(:date => @date)

我确实有这张桌子

create_table :swimming_classschedules do |t|
  t.integer :slot_id
  t.integer :coach_id
  t.integer :level_id
  t.string :note

  t.timestamps
end


create_table :swimming_slots do |t|
  t.string :date
  t.string :start
  t.string :end

  t.timestamps
end

我怎么得到这个错误

Association named 'swimming_slots' was not found; perhaps you misspelled it?

更新 2

将此行添加到 Swimming::Classschedule 模块

add this line to Swimming::Classschedule module

belongs_to :swimming_slots ,:class_name=>'Swimming::Slot',:foreign_key => "slot_id"

belongs_to :swimming_slots ,:class_name=>'Swimming::Slot',:foreign_key => "slot_id"

将连接更改为

@schedules= Swimming::Classschedule.joins(:swimming_slots).where(:swimming_slots =>{:date => @date})

现在可以了

推荐答案

您通过关联名称加入.例如,如果你有一个像

you pass the association name to joins. for example, if you have an association like

has_many :swimming_slots, class_name: 'Swimming::Classschedule'

然后你通过 swimming_slots 并且 rails 会为你做连接.

then you pass swimming_slots and rails will do the joins for you.

User.joins(:swimming_slots)

更新:

如果 slot_id 指的是 swimming_slots 表中的记录,你应该有类似

if slot_id refers to a record in the swimming_slots table, you should have something like

belongs_to :slot, class_name: 'Swimming::Slot'

在您的课程表模型中.如果你有那个,你应该能够做到

in your class schedule model. If you have that, you should be able to do

Swimming::Classschedule.joins(:slot)

这篇关于rails 连接模块名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆