rails return 个具有共同属性的元组
rails return tuples with common attributes
我想显示所选导演的所有电影。路线和控制器工作正常。但是,视图中显示的过滤后的电影都是相同的。例如,我有四部电影,其中两部是同一个导演。我想要的是在视图页面中显示这两个不同的元组,但是显示的两个元组是相同的。这是控制器代码:
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
else
flash[:notice] = "'#{@movie.title}' has no director information"
redirect_to root_path
end
end
我尝试了 find_by_sql 和 find_by_all 两种方法来查找元组,但它们都得到了相同的结果。
这是查看代码:
%tbody
- @movies.each do |movie|
%tr
%th= @movie.title
%th= @movie.rating
%th= @movie.release_date
我是 rails 的新手,如有任何意见或建议,我们将不胜感激。
在您的视图代码中,您正在使用实例变量 @movie
,它 returns 是您从控制器代码第 2 行进行的原始搜索结果。要在遍历 @movies 时查看每部电影,您需要使用在块中声明的局部变量。
%tbody
- @movies.each do |movie|
%tr
%th= movie.title
%th= movie.rating
%th= movie.release_date
如果这令人困惑,您可以完全更改块变量的名称。这不会改变结果,但可能更具可读性。
%tbody
- @movies.each do |matched_movie|
%tr
%th= matched_movie.title
%th= matched_movie.rating
%th= matched_movie.release_date
编辑:(有人建议我在这个答案中添加我的评论。)
这与您的问题无关,但在第 6 行执行搜索的更标准 Rails 方式是 @movies = Movie.where(director: @director)
。更好的是,由于您不需要在视图中使用@director,您可以这样做:
director = @movie.director
@movies = Movie.where(director: director)
我想显示所选导演的所有电影。路线和控制器工作正常。但是,视图中显示的过滤后的电影都是相同的。例如,我有四部电影,其中两部是同一个导演。我想要的是在视图页面中显示这两个不同的元组,但是显示的两个元组是相同的。这是控制器代码:
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
else
flash[:notice] = "'#{@movie.title}' has no director information"
redirect_to root_path
end
end
我尝试了 find_by_sql 和 find_by_all 两种方法来查找元组,但它们都得到了相同的结果。 这是查看代码:
%tbody
- @movies.each do |movie|
%tr
%th= @movie.title
%th= @movie.rating
%th= @movie.release_date
我是 rails 的新手,如有任何意见或建议,我们将不胜感激。
在您的视图代码中,您正在使用实例变量 @movie
,它 returns 是您从控制器代码第 2 行进行的原始搜索结果。要在遍历 @movies 时查看每部电影,您需要使用在块中声明的局部变量。
%tbody
- @movies.each do |movie|
%tr
%th= movie.title
%th= movie.rating
%th= movie.release_date
如果这令人困惑,您可以完全更改块变量的名称。这不会改变结果,但可能更具可读性。
%tbody
- @movies.each do |matched_movie|
%tr
%th= matched_movie.title
%th= matched_movie.rating
%th= matched_movie.release_date
编辑:(有人建议我在这个答案中添加我的评论。)
这与您的问题无关,但在第 6 行执行搜索的更标准 Rails 方式是 @movies = Movie.where(director: @director)
。更好的是,由于您不需要在视图中使用@director,您可以这样做:
director = @movie.director
@movies = Movie.where(director: director)