Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
Is there a way to access values stored in has_many association in Ruby on Rails?

I have two models in Ruby on Rails, movies, and directors. A director has_many movies, and a movie belongs_to a director. I'm creating a mini-project, where if I view a Director on a page, I would like to have all movies associated with this particular author shown, along with links to these movies. I was able to make it with a movie successfully showing its Director with a link to his page, but I've been unable to accomplish this when viewing a director. All my research so far has led me to is

<%= director.movies.uniq.pluck(:name) %>

but that only shows the :name strings within an array format, which is not optimal. I would like to know if there is a way, in which I can access the id values stored in has_many. Because it has to work like an array, which saves the ids, so the program knows, which Movies belong to which Director. Please correct me if I'm wrong in this assumption, I'm still learning and will appreciate any input on this matter.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To accomplish this you will need to iterate over the array of Movie instances that belong to an instance of a Director. You can access this array (which is actually a Collection Proxy) with director.movies (assuming that director is an instance of Director). You will then be able to access the values of each instance.

Your code may look something like this:

<ul>
  <% director.movies.each do |movie| %>
    <li><%= link_to movie.name, movie_path(movie) %></li>
  <% end %>
</ul>
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda