Fetch the various fields from the query

Asked

Viewed 86 times

3

I have this darling:

@tudo = Isolated.joins("LEFT JOIN resists ON resists.isolated_id = isolateds.id").joins("LEFT JOIN genes ON genes.isolated_id = isolateds.id LEFT JOIN stats ON stats.gene_id = genes.id LEFT JOIN mutations ON mutations.id = stats.mutation_id").all

I want to get model fields Gene, as for example the field name. When I do @everything on the Rails console (Rails c), I see this:

Isolated Load (4.4ms)  SELECT `isolateds`.* FROM `isolateds` LEFT JOIN resists ON resists.isolated_id = isolateds.id LEFT JOIN genes ON genes.isolated_id = isolateds.id LEFT JOIN stats ON stats.gene_id = genes.id LEFT JOIN mutations ON mutations.id = stats.mutation_id
=> #<ActiveRecord::Relation [#<Isolated id: 1, name: "xpto", disease: "sklhafl", n_samples: 1, origin_id: 1, organism_id: 3, created_at: "2015-03-23 16:21:20", updated_at: "2015-03-23 16:21:20">, #<Isolated id: 2, name: "khjlsdkf", disease: "lkajsçdl", n_samples: 123, origin_id: 1, organism_id: 1, created_at: "2015-03-26 18:57:02", updated_at: "2015-03-26 18:57:02">,...

That is, only data from Isolated, even though the tables are together. if made @tudo.select("genes.name"), on the console of the Rails give me this:

#<ActiveRecord::Relation [#<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, #<Isolated id: nil, name: nil>, ...]>

and when in the html.erb file: @tudo.gene.name gives me error, how can I get the name of the gene?

  • 2

    I’ve found it enough to do: @tudo = @tudo.select("genes.name as genename")

  • Add your comment to a question, and accept it as an answer, as it may help other users with the same problem, or similar problems.

2 answers

1

I’ve found it enough to do: @tudo = @tudo.select("genes.name as genename")

0

Catherine, as defined, when we call @tudo, the server answers us with a list. In this case, when calling @tudo.gene, it is normal that you miss a mistake.

To receive a list of gene names, you could use the map method.

@tudo.map(&:name)

What the method map does is execute the command that comes after the two points (":") for each of the items in your gene list and return the result in the form of an array.

I hope I’ve helped =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.