Search code examples
ruby-on-railsransack

Ransack search in show action updates associated object's user_id


I want to search a list of operators that belong to a user on the user's show view with the Ransack gem. However I get a completely unexpected result. IT UPDATES THE USER_ID FOR THE OPERATOR.

Check it out:

I am using Rails 5 and the ransack gem. I have a search form on a User's show view. This is the form:

<%= search_form_for @q, url: current_user, class: "form-group input-group-btn" do |f| %>

When I search, the following occurs:

(0.5ms)  BEGIN
SQL (0.9ms)  UPDATE "operators" SET "user_id" = NULL WHERE "operators"."user_id" = $1 AND "operators"."id" = 3  [["user_id", 3]]
(0.8ms)  COMMIT

So, this search form is updating the associated associated object's user_id.

Here is my show action in the Users controller:

def show
    @user = User.find(params[:id])

    @q = @user.operators.ransack(params[:q])
    @user.operators = @q.result(distinct: true).order("created_at ASC")
end

Here is the complete form:

<%= search_form_for @q, url: current_user, class: "form-group input-group-btn" do |f| %>

 <div class="input-group">

   <%= f.search_field :name_cont_any, class: "form-control" %>

     <span class="input-group-btn">

     <%= button_tag( :class => "btn btn-primary") do %>
       <i class='fa fa-search'></i>
     <% end %> 

  </span>

 </div>

<% end %>

Solution

  • send only the @operators variable

    def show
        @user = User.find(params[:id])
    
        @q = Operator.where(user_id: current_user).ransack(params[:q])
        @operators = @q.result(distinct: true).order("created_at ASC")
    end