I will briefly cover creating a list of check boxes on a website that will allow data to be saved to the database. This can be done using a standard form and post or using Ajax. This article will cover the form/post method.
For this example I will have a feature model and a client model. There is a many to many relationship between these two models using a subscription model.
We’ll start with a view template that just lists all available features:
<ul> <% for feature in @features %> <li><%= feature.name %></li> <% end %> </ul>
Now let’s put it inside a form, and checkbox to each list item, and put an update button on it:
<% form_tag "/path/to/post/to", :method => :put do %> <ul> <% for feature in @features %> <li> <%= check_box_tag 'feature_ids[]', feature.id, subscribed_to?(feature) %> <%= feature.name %></li> <% end %> </ul> <p> <%= submit_tag 'Update' %> </p> <% end %>
OK, there are a couple things here that I will explain. Notice the use of the square brackets in the check_box_tag name. This allows there to be a list of items with the same name and have them passed as an array in the params. Also notice that instead of stating true or false as the third element of the check_box_tag, I’ve used a helper method. This allows me to say that the check box is checked if the client is subscribed to that feature. That code could look something like:
def subscribed_to?(feature) @client.features.include?(feature) end
We also need a little code in our controller to populate things:
def subscriptions
@client = Client.find(params[:id])
@features = Feature.all
end
The action used by the “/path/to/post/to” should now have everything it needs to update the database. There is an array of feature_ids that can be passed to a model to update the database. Then you might want to do something like set a flash message to let the user know what happened and redirect to an appropriate page.
def set_subscriptions
do_something_with_this_array(params[:feature_ids])
flash[:notice] = ‘Subscriptions Updated’
redirect_to ‘/someplace/relevant’
end
This is not a complete tutorial by any means. Hopefully it helps point you in the right direction. Railscast #52 covers this same topic and may also be a helpful resource.