开发者

How to pre-check checkboxes in formtastic

开发者 https://www.devze.com 2022-12-29 02:06 出处:网络
I have a form I\'m trying to set up ... Users can have many posts, and each post can have many people watching it.

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' } 开发者_Go百科%>
      <label>Tag Users (they will get notified of this update)</label>
       <%= f.input :user, :as => :check_boxes, :label => '&nbsp;', :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}


For anyone else having the same issue:

<%= f.input :some_input, :as => :boolean, :input_html => { :checked => 'checked' } %>


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])}] } %>


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


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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消