【问题标题】:How to pre-check checkboxes in formtastic如何在formtastic中预先检查复选框
【发布时间】:2010-04-29 05:23:09
【问题描述】:

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

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

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

进一步澄清......这是我现在让它做我想做的事情的黑客方式

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

【问题讨论】:

  • pastie.org 不工作。你能把代码放在别的地方吗?
  • 完成。感谢您查看它。

标签: ruby-on-rails formtastic


【解决方案1】:

对于遇到相同问题的其他人:

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

【讨论】:

  • 如果您希望选中所有复选框,这也适用于:as =&gt; :check_boxes
  • 也可以说 :input_html => { :checked => true }
【解决方案2】:

对于多个复选框,这样:

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

【讨论】:

    【解决方案3】:

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

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

    在你的模型中..

    def some_input?
      self.some_input ? true : false
    end
    

    【讨论】:

    • 这对我不起作用。它将:some_input? 视为真实(因为它不是nil 或false)。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 2020-03-25
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2020-03-12
      相关资源
      最近更新 更多