2012-10-20 54 views
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@all_rating如果@checked.rating是空的,但它沒有做任何事情。 我試着在的index.html.haml中放入:checked => true,但是每當刷新頁面時都會檢查複選框。 每次我檢查一個特定的複選框,並點擊刷新按鈕頁面加載與選中的所有複選框。

+0

我可以問你爲什麼要編輯'index'操作中的評級嗎?編輯值通常在'edit'操作中完成。 –

+1

我的意圖不是編輯它們,但我想在第一次加載頁面時檢查所有複選框。 – UGuess

+0

僅在第一次加載頁面時選中複選框的目的是什麼?我不瞭解這裏的用例。 –

回答

0

您可以使用localstorage + JavaScript來實現此目的。在頁面加載時,檢查localstorage中屬性的值。如果設置了該值,則不要選中這些框。如果未設置值,請檢查所有框並在localstorage中設置值。

Varun

相關問題