How to pre-check checkboxes in formtastic

2019-03-12 11:12发布

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 => '&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}

4条回答
Juvenile、少年°
2楼-- · 2019-03-12 11:38

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楼-- · 2019-03-12 11:42

For anyone else having the same issue:

<%= f.input :some_input, :as => :boolean, :input_html => { :checked => 'checked' } %>
查看更多
可以哭但决不认输i
4楼-- · 2019-03-12 11:50

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

查看更多
一夜七次
5楼-- · 2019-03-12 11:54

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
查看更多
登录 后发表回答