Forum: Ruby on Rails Make a checkbox checked based on a condition?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
87e4363c61cea7fd62feee2dfcddc93a?d=identicon&s=25 Nick Coyne (nick)
on 2006-05-01 16:43
I have a series of checkboxes in a form generated as follows:

<% for user in @active_users %>
  <p><%= user.firstname + " " + user.surname%>
  <%= check_box 'assigned_tasks', 'user_id', {:index => user.id},
user.id, nil %></p>
<% 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.
D60346d9f28eb8ac662e103b5f46f9f5?d=identicon&s=25 Chuck Vose (Guest)
on 2006-05-03 18:57
(Received via mailing list)
It's a little obscure but you can find some general suggestions here:
http://api.rubyonrails.com/classes/ActionView/Help...

I remember having a hell of a time doing the same thing but I don't
remember my solution.
58c6efb8466b9f85155fe6aa9fc37fce?d=identicon&s=25 Chris T (Guest)
on 2006-05-03 18:57
(Received via mailing list)
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?(c) ?
{: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.
4229252d6391826398753b9632592c9c?d=identicon&s=25 Rich P (Guest)
on 2006-05-16 05:10
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?(c) && {: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 topic is locked and can not be replied to.