Controller
Controller

Reputation: 529

rails form_tag with checkboxes

I know there may be 1 or 2 similar questions,but none of them helped me understand where I am wrong in the following. I have the following haml form in my view:

= form_tag movies_path,:id=>"ratings_form", :method => :get do
  Include: 
  -  @all_ratings.each_with_index do |rating, index|
  = rating
  = check_box_tag "ratings[]", rating, @selected_ratings.include?(rating), id:"ratings_#{rating}"

and in my controller:

def index
    sorting=params[:sorting_on_a_column]
    if sorting=='1'
       @sort='title'
       @movies=Movie.order('title')
    elsif sorting=='2'
       @sort='date'
       @movies=Movie.order('release_date')
    else
       @movies=Movie.all
    end
    @all_ratings=Movie.select(:rating).map(&:rating).uniq
    @selected_ratings = (params["ratings"].present? ? params["ratings"] : @all_ratings)
    @movies = @movies.where(":rating IN (?)", params["ratings"]) if params["ratings"].present? and params["ratings"].any?
     end

My target on the above is to sort movies by title or release_date(which it does) and also show only the movies that correspond to the checked checkboxes.I am new to Ruby and Rails, so I would really appreciate your help.Thank you in advance!

Upvotes: 2

Views: 5251

Answers (1)

Zach Kemp
Zach Kemp

Reputation: 11904

A few things to think about:

1 - How many possible ratings are there? You're assigning @all_ratings based on what appears in another model's database table. If there isn't a Rating model, and the complete list of ratings will grow over time, there probably should be.

2 - You can set up your check box tag like this:

- @all_ratings.each_with_index do |rating, index|
  = label_tag "rating_#{rating}", rating
  = check_box_tag "ratings[]", rating, @selected_ratings.include?(rating), id: "rating_#{rating}"

This will give you an array of string values in params["ratings"] that should work in your code as-is.

The label tag is set up so that when you click on the text, it selects the appropriate check box. .each_with_index is used to provide a unique ID for each rating, since as of now, they don't have one from the database (it matches the "rating_#{index}" id declaration in the check_box_tag).

Upvotes: 3

Related Questions