Ruby Rails:为什么我的搜索不起作用?

Ruby on Rails: Why isn't my search working?

在我的 RoR 应用程序中,我允许用户 select 他们想要向其发送电子邮件的联系人。用户 select 通过表单上的复选框联系这些联系人。我正在尝试添加搜索功能,以便用户可以按名字搜索,并且只显示与搜索相匹配的联系人的复选框。

为此,我尝试在视图中使用此代码:

<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">
    <%= form_tag '/emails/contact_search', :method => 'get' do %>
      <p>
        <%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
        <%= submit_tag "Search", :name => nil %>
      </p>
    <% end %>
    <label>Contacts</label></br>
    <%= f.collection_check_boxes :contact_ids, @contacts, :id, :fullname %>
</div>

其中 @contacts 实例变量保存从控制器中搜索返回的联系人。

当用户单击搜索按钮时,应调用以下控制器操作。

def contact_search
    @email.recipients.build
    @useraccounts = Useraccount.where(user_id: session[:user_id])
    @contacts = Contact.contacts_search(params[:search_string])
    if @contacts.empty?
        flash.now[:alert] = "There are no contacts with that name."
        @contacts = Contact.all
    end
    render :action => "new"
end

这个控制器动作使用contact_search方法,在Contact.rb模型中:

def self.contact_search(search_string)
    self.where("firstname LIKE ?", search_string)
end

我在路线中也有contact_search

post 'emails/contact_search', :to => 'emails#contact_search'
get 'emails/contact_search', :to => 'emails#contact_search'

但出于某种原因,当用户单击搜索时,他们会在表单上看到 NoMethodError in Emails#create undefined method 'each' for nil:NilClass。报错如图。

我不知道为什么这不起作用,有人可以帮忙吗?

根据 erb,我猜你在 form_for 块中有一个 form_tag...你不能那样做

当您点击提交时,操作将转到第一个表单操作...这可能是一个创建

最好将您的 form_tag 移到您之前的 form 块之外...

您的模态名称 (Useraccount) 似乎不正确,必须是 UserAccount.

另请注意

当我们使用 where 查询和 ActiveRecord 模态时,我们永远不会得到 NIL 对象,除非我们有错误的模态名称。