check_box problem

I have used check_box_tag method to store the select value in the string data type attribute in database with multiple selection seperated by comma. My problem is that when I need to edit that object(row) how can I make the check_box checked for the value in that string data type attribute of my database.

Mr. Bless wrote:

I have used check_box_tag method to store the select value in the string data type attribute in database with multiple selection seperated by comma. My problem is that when I need to edit that object(row) how can I make the check_box checked for the value in that string data type attribute of my database.

maybe pass it :selected => true ?

The third argument that you pass to check_box_tag is either true or false, and if it's true, the box is checked. I'm using it like this:

<%= check_box_tag s.id, '1', (params[:selected_services] && params[:selected_services].include?(s.id.to_s)) %>

The third argument looks to see if there's a params[:selected_services] value and then checks to see whether or not the current value is included in the params (which is ugly, but it works so far). You might be able to modify my example and generate an array from your database values (object.atr.split(',') or something), passing it to include.

...or something like that.

Thanks a lot. But I still got one more question. Since I have stored the data in comma separated values in database field. Now while editing I have to show the checked only for those items that were saved in the database. Writing each and every condition using if else is not what I am looking for. I want something that is efficient and less code. Plz... Help

You can always work on efficiency later... :slight_smile: Honestly, I'm not good at writing efficient code yet, so I tend to find something that works first and then worry about efficiency. If you're not dealing with immense amounts of data, then a few thousandths of a second here and there usually aren't worth fretting over until you've covered other more important aspects of your app.

It doesn't seem like storing a CSV in a database is terribly efficient to begin with - it almost makes you iterate over the field to get the values. Perhaps using a separate table and an AR association would work better, but I'm not sure what you're working with.

-Kyle