0

我对rails很陌生,试图找出解决方法,但遇到了路障,

我正在尝试根据用户检查的复选框显示数据库中具有特定评级的所有电影。这是复选框和电影表的表格

-#  This file is app/views/movies/index.html.haml
%h1 All Movies
= form_tag movies_path, :id => "ratings_form", :method => :get do
  Include:
  - @all_ratings.each do |rating|
    = rating
    = check_box_tag "ratings[#{rating}]",  1, rating
  = submit_tag 'Refresh'
%table#movies
  %thead
    %tr
      %th Movie Title
      %th Rating
      %th Release Date
      %th More Info
  %tbody
    - @movies.each do |movie|
      %tr
        %td= movie.title 
        %td= movie.rating
        %td= movie.release_date
        %td= link_to "More about #{movie.title}", movie_path(movie)

= link_to 'Add new movie', new_movie_path

这是电影控制器

class MoviesController < ApplicationController

  def show
    id = params[:id] # retrieve movie ID from URI route
    @movie = Movie.find(id) # look up movie by unique ID
    # will render app/views/movies/show.<extension> by default
  end

    def index
        @all_ratings = Movie.all_ratings
    @movies = Movie.where(:ratings)
    end

  def new
    # default: render 'new' template
  end

  def create
    @movie = Movie.create!(params[:movie])
    flash[:notice] = "#{@movie.title} was successfully created."
    redirect_to movies_path
  end

  def edit
    @movie = Movie.find params[:id]
  end
  def update
    @movie = Movie.find params[:id]
    @movie.update_attributes!(params[:movie])
    flash[:notice] = "#{@movie.title} was successfully updated."
    redirect_to movie_path(@movie)
  end

  def destroy
    @movie = Movie.find(params[:id])
    @movie.destroy
    flash[:notice] = "Movie '#{@movie.title}' deleted."
    redirect_to movies_path
  end
end

因为我无法弄清楚为什么没有电影放映,所以数据库中肯定有一些。我觉得 :ratings 中没有任何内容,但不确定是否有任何其他方式可以引用它们

4

1 回答 1

0

首先将列评级移动到评级。

 = form_tag movies_path, :id => "ratings_form", :method => :get do
   Include:
   - Movie.all_ratings.each do |rating|
     = rating
     = check_box_tag "ratings[#{rating}]",  0, rating
   = submit_tag 'Refresh'

在控制器中,您可以找到评级数组的位置

class MoviesController < ApplicationController

  def index
    @movies = Movie.where(rating: params[:ratings].keys)
  end

  #....
end

一件事 - 在您发送评级参数之前,您会得到空数组!通过以下方式简单解决此问题:

class MoviesController < ApplicationController

  def index
    if params[:ratings].present?
      @movies = Movie.where(rating: params[:ratings].keys)
    else
      @movies = Movie.all
    end
  end

  #....
end

或在模型范围内执行此操作(这是更好的选择!)

如果有人添加更优雅的解决方案会很棒:)

于 2013-11-03T18:57:57.487 回答