kchen kchen - 9 months ago 111
Ruby Question

rails return tuples with common attributes

I want to display all the movies by selected director. Routes and controller work fine. However, the filtered movies shown in view are all the same. For example, I have four movies of which two have the same director. What I want is to show these two different tuples in view page, but the shown two tuples are the same. This is the controller code:

def find_movies_by_same_director
@movie = Movie.find(params[:id])
@director = @movie.director
if (not @director.nil?) and (not @director.empty?)
#@movies = Movie.find_all_by_director(@director) if (not @director.nil?) and (not @director.empty?);
@movies = Movie.find_by_sql("SELECT * FROM movies i WHERE i.director == '#{@director}'")
render :director
flash[:notice] = "'#{@movie.title}' has no director information"
redirect_to root_path

I try both ways, find_by_sql and find_by_all, to find the tuples, but they both get the same results.
This is the view code:

- @movies.each do |movie|
%th= @movie.title
%th= @movie.rating
%th= @movie.release_date

I'm new to rails, so any comments or suggestion will be appreciated.

Answer Source

In your view code, you are using the instance variable @movie, which returns the result of your original search from line 2 of your controller code. To see each movie as you iterate through @movies, you need to use the local variable that you are declaring in the block.

- @movies.each do |movie|
    %th= movie.title
    %th= movie.rating
    %th= movie.release_date

If that's confusing, you might change the name of the block variable entirely. This doesn't change the result but might be more readable.

- @movies.each do |matched_movie|
    %th= matched_movie.title
    %th= matched_movie.rating
    %th= matched_movie.release_date