Ruby on Rails:搜索后选中复选框

时间:2017-02-21 20:11:42

标签: ruby-on-rails

在我的RoR应用程序中,我有一个表单,用户可以通过名字搜索他们的联系人,并选择他们想要发送电子邮件的联系人。我的问题是,在搜索了#34; Tom"并选择" Tom"的复选框后,如果他们然后重置搜索以显示所有复选框" Tom"不再被选中。

有人可以告诉我这是如何分类的吗?

视图中的代码是:

theMagazine

搜索的控制器代码为:

<div class="panel-body">
    <%= form_tag '/emails/contact_search', :method => 'get' do %>
      <p>
        <%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
        <%= submit_tag "Search" %>
      </p>
    <% end %>
    <%= form_for(@email) do |f| %>
        <fieldset>
            <div class="form-group">
                <label>From Email Address</label></br>
                <% @useraccounts.each do |useraccount| %>
                    <%= f.radio_button :account_id, useraccount.account_id, :checked => false %>
                    <%= f.label :account_id, useraccount.account.email, :value => "true"  %><br>
                <% end %>
            </div>
            <div class="form-group">
                <label>Contacts</label></br>
                <%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname, checked: @selected_contact_ids %>
            </div>
            <div class="form-group">
                <label>Groups</label></br>
                <%= f.collection_check_boxes :group_ids, Group.where(user_id: session[:user_id]), :id, :name ,{ prompt: "name" } %>
            </div>
            <div class="form-group">
                <label>Attachment</label>
                <%= f.file_field :attachment, :size => 42 %><br>
            </div>
            <div class="actions">
                <%= f.submit "Continue", {:class => 'btn btn-primary '} %>
                <%= render "/error_messages", :message_header => "Cannot save: ", :target => @email %>  
            </div></br>

        </fieldset> 
    <% end %>
</div>

在模型中:

 def contact_search
    @email = Email.new(session[:email_params])
    @email.current_step == session[:email_step]
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.contact_search(params[:search_string])
    if @contacts.empty?
        flash[:notice] = "There are no emails with that subject"
        @contacts = Contact.all
    end
    render :action => "new"
 end
private
def email_params
    params.require(:email).permit(:subject, :message, :account_id, { contact_ids: [] }, { group_ids: [] }, :attachment)
end

我无法弄清楚如何在用户搜索其他内容后重新选中复选框或重置搜索,有人可以了解如何实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

这似乎是Rails中那些模糊且记录不完整的功能之一。如果要将id检入checked参数

,则必须执行的操作是传递数组
= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname, checked: @selected_contact_ids

然后将检查包含id 1,2和3项的复选框。您需要以某种方式明显地从控制器传递此数组。 E.g。

@selected_contact_ids = email_params.fetch(:contact_ids, [])