Utilizzare ActiveRecord trovare Risultato di 5 tabelle nidificate
-
25-09-2019 - |
Domanda
Ho un utente modello (: nome,: password: e-mail), e il modello di evento (: nome,: ecc) e il modello di interesse (: nome)
Poi ho creato due uniscono le tabelle -> UsersInterests e EventsInterests; ciascuno non contiene una chiave primaria e solo composto user_id / interest_id e event_id / interest_id rispettivamente.
Sto cercando di usare ActiveRecord per interrogare un elenco di tutti gli eventi in cui l'interest.id di EventsInterests = interest.id di UsersInterests
sto usando has_many e belongs_to rapporti con la Nested Loop Plugin
I miei modelli assomigliano in modo =>
user.rb
has_many :users_interests
has_many :interests, :through => :users_interests
event.rb
has_many :events_interests
has_many :interests, :through => :events_interests
interest.rb
belongs_to :users , :through => :users_interests
belongs_to :events , :through => :events_interests
users_interests.rb
belongs_to :users
belongs_to :interests
events_interests.rb
belongs_to :interests
belongs_to :events
Se l'utente @ = User.find (1), Come faccio a interrogare gli eventi che un utente potrebbe essere interessato a?
mi si avvicinò con questa => @ Events.find (: all,: condizioni => = EventsInterests.interest_id UsersInterests.interest_id) ??
, ma ho l'errore
undefined method `interest_id' for UsersInterests(user_id: integer, interest_id: integer):Class
umm..wtf? qualsiasi aiuto ragazzi .... Sono stato a questo per come 4 giorni
Soluzione
In primo luogo, hop nella console e assicurarsi che tutto il lavoro relazioni:
User.first.events
User.first.interests
Events.first.users
Interests.first.users
Interests.first.events
# ... and so
Giusto per chiarire, a elenchi di utenti i suoi interessi, e si desidera ottenere un elenco degli eventi che corrispondono questi interessi?
User.first.interests.collect { |interest| interest.events }.uniq
Non particolare efficiente, ma efficace e facile da comprendere.
Si potrebbe usare User.first.interests_singular_ids
per ottenere gli ID e passare che a un find () con interest_id IN(...)
quella lista, anche. Non sono sicuro quanto più veloce sarebbe, però.