rails joins with module name

青春壹個敷衍的年華 提交于 2020-03-01 09:39:39

问题


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

UPDATE

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

and I do have this table

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

Howcome I got this error

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

update 2

add this line to Swimming::Classschedule module

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

and

change joins to

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

Now it works


回答1:


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

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

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

User.joins(:swimming_slots)

UPDATE:

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)


来源:https://stackoverflow.com/questions/15307290/rails-joins-with-module-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!