1

How do I implement a check_box_tag with pre-checked boxes which match the values contained in an instance variable @array:

= form_tag xxx_path, :method => :get do 
  - @all_names.each do |name|
    = rating
    = check_box_tag "names[#{name}]", CHECKED IF name in @array
  = submit_tag 'Refresh'

Edit - Controller first:

  def index
    if params[:ratings]
      @filtered_ratings = params[:ratings]
      @movies = Movie.find(:all, :conditions => ["rating IN (?)", @filtered_ratings], :order => params[:sort])
    else
      @movies = Movie.find(:all, :order => params[:sort])   
    end
  end

Now view:

= form_tag movies_path, :method => :get do
  Include: 
  - @all_ratings.each do |rating|
    = rating
    = check_box_tag "ratings[#{rating}]", 1, @filtered_ratings.include?(rating) ? true : false
= submit_tag 'Refresh'
4

1 回答 1

1

尝试这个:

= form_tag xxx_path, :method => :get do 
  - @all_ratings.each do |rating|
    = rating
    = check_box_tag "ratings[#{rating}]", 1, @filtered_ratings.include?(rating) ? true : false
  = submit_tag 'Refresh'

在控制器中:

def index
  @filtered_ratings = params[:ratings] || [] # if no params[:ratings] then assign empty array
  @movies = Movie.order(params[:sort])
  @movies = @movies.where(rating: params[:ratings]) if params[:ratings].present?
end
于 2013-01-29T21:45:08.207 回答