问题
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