我想按所选导演显示所有电影。路由和控制器工作正常。但是,视图中显示的已过滤电影都是相同的。例如,我有四部电影,其中两部有相同的导演。我想要的是在视图页面中显示这两个不同的元组,但显示的两个元组是相同的。这是控制器代码:
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的新手,所以任何意见或建议都会受到赞赏。
答案 0 :(得分:1)
在视图代码中,您使用的是实例变量@movie
,它从控制器代码的第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)