我引用这些rails params的方式有什么问题?

时间:2013-11-03 18:25:41

标签: ruby-on-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

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

1 个答案:

答案 0 :(得分: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

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

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