Make a checkbox checked based on a condition?

I have a series of checkboxes in a form generated as follows:

<% for user in @active_users %>

<%= user.firstname + " " + user.surname%> <%= check_box 'assigned_tasks', 'user_id', {:index => user.id}, user.id, nil %>

<% end %>

I’d like to have one of them selected when user.id is equal to the value
of the logged in user, stored in session[:user_id]

How do I do that?

thx
N.

It’s a little obscure but you can find some general suggestions here:
http://api.rubyonrails.com/classes/ActionView/Helpers/FormHelper.html#M000394

I remember having a hell of a time doing the same thing but I don’t
remember my solution.

I’ve just had to do something similar and did this (though I have to
say, I’m not wild about it - seems a pretty messy way to do it):

<% for c in @categories %>
<%= check_box(“category”, c.id, (@selected_categories.include?© ?
{:checked => ‘checked’} : {:checked => false} )) %> <%= c.name %>
<% end %>

Basically, this was to allow an edit of an entry which was a member of a
number of categories, with @selected_categories being the categories the
entry is currently a member of. the bit in parentheses tests whether the
category is included in @selected_categories, if so it returns :checked
=> ‘checked’, otherwise {:checked => false}

However, this feels a bit like a hack to me, and there’s got to be a
better way. Hope this helps in the meantime.

This worked for me with one minor change. The checkbox is unchecked by
default so the option parameter condition can be written more simply as:

(@selected_categories.include?© && {:checked => ‘checked’})

Chris T wrote:

I’ve just had to do something similar and did this (though I have to
say, I’m not wild about it - seems a pretty messy way to do it):

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs