2017-02-21 122 views
1

在我的RoR應用程序中,我的功能允許用戶選擇要發送電子郵件的聯繫人。我想添加到此功能,以便用戶可以搜索聯繫人。Ruby on Rails:在表單上搜索collection_check_boxes

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

是否有可能建立在這個通過添加允許用戶搜索複選框上方的搜索欄:

目前,該聯繫人的複選框,用戶可以選擇通過顯示在views/emails/form.html.erb名字複選框?

回答

0

你可以有一個窗體來處理一個不顯眼的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 %>") 
}) 

這是一個非常簡單的考試唔......我不處理重複......如果你兩次搜尋相同的東西...