如何预先检查formtastic中的复选框

con*_*t47 16 ruby-on-rails formtastic

我有一个表单,我正在尝试设置...用户可以有很多帖子,每个帖子都可以有很多人观看它.

Watch模型以多态形式设置为"可观察",因此它可以应用于不同类型的模型.它具有user_id,watchable_id,watchable_type和时间戳作为属性/字段.

这是非常好的,所以当人们评论帖子时,观看帖子的用户可以收到有关它的电子邮件.

我要做的是向用户显示他们可以在每个帖子上标记的用户列表,这不是问题.这就是我现在正在使用的

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 %>
Run Code Online (Sandbox Code Playgroud)

这个问题是,当你去编辑更新/发布时...所有的复选框都是预先检查的......我希望它只预先检查当前正在观看帖子的用户.

为了进一步澄清......这是我现在想要做的事情的hacky方式

<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>
Run Code Online (Sandbox Code Playgroud)

其中@watches只是一个用户ID数组

@watches = @update.watches.map{|watcher| watcher.user_id}
Run Code Online (Sandbox Code Playgroud)

Joh*_*man 20

对于其他有同样问题的人:

<%= f.input :some_input, :as => :boolean, :input_html => { :checked => 'checked' } %>
Run Code Online (Sandbox Code Playgroud)

  • 也可以这么说:input_html => {:checked => true} (4认同)

Mun*_*sim 7

对于多个复选框,这样:

<%= f.input :tags, :as => :check_boxes, :collection => some_map.collect { |c| [c[:name], c[:id], {:checked=> tag_ids.include?(c[:id])}] } %>
Run Code Online (Sandbox Code Playgroud)