A
A
Anton Ipatov2019-11-13 16:56:59
Digital certificates
Anton Ipatov, 2019-11-13 16:56:59

Sorting multiple models in one controller?

Hello, I'm using Ruby on Rails 5.2.3 and Mongoid 7.0.
I need to be able to sort multiple models (Item and Text) in one controller.
Now only Item or Text is sorted, it is necessary that Position is set in relation to each other.

class UsersController < ApplicationController
  def sort
    params[:item].each_with_index do |id, index|
      Item.where(id: id).update_all(position: index + 1)
    end
    head :ok
  end
  def admin
    @user_items = @user.user_feed
  end
end

admin.html.erb
<div id="items" data-url="<%= sort_users_path %>">
    <%= render partial: 'users/user_item', collection: @user_items %>
  </div>

_user_item.html.erb
<% if user_item[:title].present? %>
  <div id="item_<%= user_item[:id] %>">
    <%= user_item[:position] %>
  </div>
<% end %>

<% if user_item[:text].present? %>
  <div id="item_<%= user_item[:id] %>">
    <%= raw user_item[:position] %>
  </div>
<% end %>

User.rb
def user_activity
    activity_items = []

    items.each do |item|
      activity_item = {}
      activity_item[:id] = item.id
      activity_item[:url] = item
      activity_item[:title] = item.title
      activity_item[:position] = item.position
      activity_item[:item_link] = item.url

      activity_items << activity_item
    end

    texts.each do |text|
      activity_item = {}
      activity_item[:id] = text.id
      activity_item[:url] = text
      activity_item[:text] = text.text
      activity_item[:position] = text.position

      activity_items << activity_item
    end
    
    activity_items.sort_by! { |activity_item| activity_item[:position] }
    activity_items
  end



  def user_feed
    activity_items = user_activity

    activity_items.sort_by! { |activity_item| activity_item[:position] }
    activity_items
  end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
entermix, 2018-10-27
@calirails

https://downforeveryoneorjustme.com/sep23.ru

A
Anton Ipatov, 2019-11-13
@IpatovAnton

Everything turned out to be easier than I thought.

def sort
    params[:item].each_with_index do |id, index|
      Item.where(id: id).update_all(position: index + 1)
      Text.where(id: id).update_all(position: index + 1)
    end
    head :ok
  end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question