uno-molti-molti soci trovano condizioni
-
05-07-2019 - |
Domanda
Ho i seguenti modelli:
project.rb
has_many :tasks
task.rb
belongs_to :project
has_many :assignments
has_many :users, :through => :assignments
user.rb
has_many :assignments
has_many :tasks, :through => :assignments
assignment.rb
belongs_to :task
belongs_to :user
Quindi, per esempio: Project.first.title # = > & Quot; Manhattan " Project.first.tasks.map (& amp;: name) # = > ['Trova scienziati', 'Trova denaro', 'Trova posizione'] Project.first.tasks.first.users.map (& amp;: full_name) # = > ["James Maxwell", "Evariste Galois", "Jules Verne"]
La mia prima domanda è: Come posso trovare tutti i nomi delle persone possibilmente con il simbolo da processare in un colpo solo, ho provato:
Project.first.tasks.users.full_name # = > E NON RIUSCITO
Project.first.tasks.map (& amp;: users) .full_name # = > E NON RIUSCITO
Project.first.tasks.map (& amp;: users) .map (& amp;: full_name) # = > E NON RIUSCITO
Qualche idea?
E penso che questa seguente domanda possa trovarsi nello stesso parco palla:
Come posso trovare un progetto con condizioni che cercano l'attributo 'full_name' degli utenti i suoi compiti?
Esempio
Project.all (: include = > {: task = >: utenti},: condizioni = > ['task.user.full_name LIKE?', query]) #questo errore
Penso che il problema sia in "task.users".
Grazie a tutti, buon Ringraziamento!
Soluzione
Per il primo ti consigliamo di fare qualcosa del genere:
Project.first.tasks.map { |t| t.users.map(&:full_name) }.flatten
Il motivo di ciò è che si desidera scorrere tutte le attività, quindi tutti gli utenti in ciascuna attività. Senza l'appiattimento questo ti darebbe un array bidimensionale.
E per la seconda la tua scoperta dovrebbe essere:
Project.all(:include => {:tasks => :users}, :conditions => ['users.full_name LIKE ?', query])
Scrivere users.full_name
implica al motore SQL che stai cercando il campo full_name
nella tabella users
.