问题
I have a form I'm trying to set up ... Users can have many posts, and each post can have many people watching it.
The Watch model is set up polymorphically as 'watchable' so it can apply to different types of models. It has a user_id, watchable_id, watchable_type and timestamps as attributes/fields.
This is soley so that when people comment on a post, users watching the post can get an email about it.
What I'm trying to do is show the user a list of users that they can tag on each post, which is not problem. This is what I'm using right now
http://pastie.org/940421
<% semantic_form_for @update do |f| %>
<%= f.input :subject, :input_html => { :class => 'short' } %>
<%= f.input :site, :include_blank => false, :input_html => { :class => 'short' } %>
<label>Tag Users (they will get notified of this update)</label>
<%= f.input :user, :as => :check_boxes, :label => ' ', :wrapper_html => { :class => "radiolist clearfix" }, :for => :watch, :name => "Watch" %>
<%= f.input :note, :label => 'Update'%>
<% f.buttons do %>
<%= f.commit_button :button_html => { :class => 'submit' } %>
<% end %>
<% end %>
The problem with this, is that when you go to edit an update/post ... all the checkboxes are prechecked ... I want it to pre-check only users who are currently watching the post.
To further clarify ... this is the hacky way I'm getting it to do what I want right now
<ul class="radiolist clearfix">
<% @users.each do |user| %>
<li>
<%= check_box_tag 'user_ids[]', user.id, @watches.include?(user.id) ? true : false -%>
<%= h user.name -%>
</li>
<% end %>
</ul>
where @watches is just an array of user ids
@watches = @update.watches.map{|watcher| watcher.user_id}
回答1:
For anyone else having the same issue:
<%= f.input :some_input, :as => :boolean, :input_html => { :checked => 'checked' } %>
回答2:
For multiple check boxes, this way:
<%= f.input :tags, :as => :check_boxes, :collection => some_map.collect { |c| [c[:name], c[:id], {:checked=> tag_ids.include?(c[:id])}] } %>
回答3:
Set the boolean attribute's value to 'true' in the controller before your render the form. That should make Formtastic default the checkbox to 'checked'.
回答4:
If you need the state of the checkbox to reflect the value of :some_input
<%= form.input :some_input, :as => :boolean, :input_html => { :checked => :some_input? } %>
In your model..
def some_input?
self.some_input ? true : false
end
来源:https://stackoverflow.com/questions/2734951/how-to-pre-check-checkboxes-in-formtastic