Home > front end >  Is there a way to access values stored in has_many association in Ruby on Rails?
Is there a way to access values stored in has_many association in Ruby on Rails?

Time:01-08

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.

CodePudding user response:

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>
  •  Tags:  
  • Related