John
John

Reputation: 275

Iterate id from the controller rails

How can I iterate in the controller, I want to replace the view and create object an for @reserve = Reserve.where(:user_id=>user.id), how can I get each user.id from @user_list = User.where.not(id: 1) and output the view as

<% @reserve.each do |a| %>
  <td><%= a.date %></td>
  <td><%= a.time %></td>
<% end %>

Model

class Reserve < ApplicationRecord
   belongs_to :user, optional: true
end

View

<% @user_list.each do |user| %>

<td><%= user.name %></td>

<% Reserve.where(:user_id=>user.id).each do |a| %>
  <td><%= a.date %></td>
  <td><%= a.time %></td>
<% end %>

Controller

@user_list = User.where.not(id: 1)

The reason why I want to do it this way is because I am using a gem for sorting and I want to place the sort on their respective model instead of using User for both reserve and user which would cause an error.

when /^created_at_/
      order("user.created_at #{ direction }") 

Upvotes: 0

Views: 68

Answers (1)

jvillian
jvillian

Reputation: 20263

If I understand your question (which I'm not sure I do), in your controller, do something like:

@user_list.each do |user|
  @user = user
  @reserve = Reserve.where(user: user) # <= do some sorting around here
  render partial: 'user_list'
end

Now, you'll have @user and @reserve available in a partial, something like:

# _user_list.html.erb

<td><%= @user.name %></td>

<% @reserve.each do |a| %>
  <td><%= a.date %></td>
  <td><%= a.time %></td>
<% end %>

Upvotes: 1

Related Questions