【问题标题】:Ruby on Rails: Search collection_check_boxes on a formRuby on Rails:在表单上搜索 collection_check_boxes
【发布时间】:2017-07-11 04:20:18
【问题描述】:

在我的 RoR 应用程序中,我的功能允许用户选择要向其发送电子邮件的联系人。我想添加此功能,以便用户可以搜索联系人。

目前,联系人显示在views/emails/form.html.erb 的复选框中,用户可以通过这些复选框进行选择:

<%= f.collection_check_boxes :contact_ids, Contact.where(user_id: session[:user_id]), :id, :firstname %>

是否可以在此基础上添加一个搜索栏,允许用户按名字搜索复选框?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 search


    【解决方案1】:

    您可以有一个表单来使用不显眼的 javascript。

    喜欢

    <div class="form-group">
      <!-- Form outside your main form... the REMOTE flag will tell rails 
           to prevent the default behaviour of a form make a request 
           for JS response --!>
      <%= form_tag contacts_path, remote: true, method: :get do  %>
        <%= input_tag :search %> 
        <%= button_tag "Search" %>
      <% end %>
    
      <div id="email-form">
        <%= form_for @email, email_path do |f| %>
          <!-- Many inputs relative with email omited--!>
    
          <div class="contact-list">
          </div>
    
          <%= f.submit 'Submit' %>
        <% end %>
    </div>
    

    有一个控制器/动作来搜索您的联系人并将其返回以用于 js 视图...

    // ContactController
    
    def index
      respond_to do |format|
        format.html { @contacts = Contact.all }
        format.js { @contacts = Contact.find_by(firstname: params[:search]) }
      end
    end
    

    并为操作 html 以附加要选择的联系人的操作/控制器提供视图

    // views/contacts/index.js.erb
    $(document).ready(function() {
      $('#contact-list').append("<%= collection_check_boxes :email, :contact_ids, @collection, :id, :firstname %>")
    })
    

    这是一个非常简单的例子......我不处理重复......如果你搜索相同的东西两次......

    【讨论】:

      猜你喜欢
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      相关资源
      最近更新 更多