2

我希望在用户第一次访问该页面时选中复选框。

这个文件是app/views/movies/index.html.haml

%h1 All Movies
= form_tag movies_path, :method => :get, :id => 'ratings_form' do
  Include:
  - @all_ratings.each do |rating|
    = rating
    = check_box_tag "ratings[#{rating}]", "1", @checked_ratings.include?(rating), :id => "ratings_#{rating}",
  = submit_tag 'Refresh', :id => 'ratings_submit'

%table#movies
  %thead
    %tr
      %th{:class => ("hilite" if @sort == "title")}= link_to "Movie Title", movies_path( :sort => "title", :ratings => @checked_ratings), :id => "title_header" 
      %th Rating
      %th{:class => ("hilite" if @sort == "release_date")}= link_to "Release Date", movies_path( :sort => "release_date", :ratings => @checked_ratings), :id => "release_date_header"
      %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

#This is my Controller

    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
    #get all the ratings available 
    @all_ratings = Movie.all_ratings
    @checked_ratings = (params[:ratings].present? ? params[:ratings] : [])
    @sort = params[:sort]
    @movies = Movie.scoped

    if @sort && Movie.attribute_names.include?(@sort)
      @movies = @movies.order @sort
    end
    id @checked_ratings.empty?
      @checked_ratings = @all_ratings
    end
    unless @checked_ratings.empty?
      @movies = @movies.where :rating => @checked_ratings.keys
    end
  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

在控制器中,如果为空但它不执行任何操作,我将其设置@checked_rating为。我尝试放入on ,但这会在每次刷新页面时检查复选框。每次我选中一个特定的复选框并点击刷新按钮时,页面都会加载所有选中的复选框。@all_rating@checked.rating:checked => trueindex.html.hamlcheck_box_tag

4

1 回答 1

0

您可以使用 localstorage + JavaScript 来实现这一点。在页面加载时,检查本地存储中的属性值。如果设置了该值,请不要选中这些框。如果未设置值,请选中所有框并在本地存储中设置值。

瓦伦

于 2012-10-22T07:42:49.357 回答