Check_box_tag - 预先检查@array中的值的条件

时间:2013-01-29 21:43:09

标签: ruby-on-rails forms model-view-controller

如何使用与实例变量@array中包含的值匹配的预先选中框来实现check_box_tag:

= 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'

编辑 - 控制器优先:

  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

现在查看:

= 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'

1 个答案:

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