19

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

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 %>

问题在于,当您去编辑更新/帖子时……所有复选框都已预先选中……我希望它仅预先检查当前正在观看该帖子的用户。

进一步澄清......这是我现在让它做我想做的事情的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>

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

@watches = @update.watches.map{|watcher| watcher.user_id}
4

4 回答 4

26

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

<%= f.input :some_input, :as => :boolean, :input_html => { :checked => 'checked' } %>
于 2011-05-18T20:59:00.927 回答
7

对于多个复选框,这样:

<%= f.input :tags, :as => :check_boxes, :collection => some_map.collect { |c| [c[:name], c[:id], {:checked=> tag_ids.include?(c[:id])}] } %>
于 2016-09-05T11:31:13.920 回答
3

如果您需要复选框的状态来反映 :some_input 的值

<%= form.input :some_input, :as => :boolean, :input_html => { :checked => :some_input? } %>

在你的模型中..

def some_input?
  self.some_input ? true : false
end
于 2012-12-08T02:22:24.337 回答
2

在呈现表单之前,在控制器中将布尔属性的值设置为“true”。这应该使 Formtastic 默认复选框为“已选中”。

于 2010-12-11T20:57:56.653 回答