Reyomi
Reyomi

Reputation: 263

Rails admin panel: User list showing bug

I'm currently trying to get used to rails by creating a website with admin and user. However, when displaying the user list in admin dashboard, for some reasons these lines appear:

[#<User id: 1, email: "[email protected]", password_digest: [FILTERED], created_at: "2022-08-09 03:47:52.264555000 +0000", updated_at: "2022-08-09 03:47:52.264555000 +0000", firstname: nil, lastname: nil, last_change: nil>, #<User id: 3, email: "[email protected]", password_digest: [FILTERED], created_at: "2022-08-19 08:32:37.086901000 +0000", updated_at: "2022-08-19 08:32:37.086901000 +0000", firstname: nil, lastname: nil, last_change: nil>, #<User id: 4, email: "[email protected]", password_digest: [FILTERED], created_at: "2022-08-19 08:32:58.497826000 +0000", updated_at: "2022-08-19 08:32:58.497826000 +0000", firstname: nil, lastname: nil, last_change: nil>]

This is the code that I used to display user list:

<%= @users.each do |hello| %>
 <%= form_with model: @user, url: '/admin/users/delete' do |f| %>
    <%= hello.email %>
    <%= hidden_field_tag( :id, hello.id) %>
    <%=f.submit "Delete"%>
  <%end%>
  <hr>
<%end%>

And this is the picture of the display I got: Image

Really appreciate if you can help. Thanks!

Upvotes: 2

Views: 68

Answers (3)

user28061806
user28061806

Reputation:

The issue here is that <%= @users.each do |hello| %> is printing out the return value of the each method, which is the original @users array itself. This is why you’re seeing the array printed as [#<User id: ...>]. To fix this, change <%= @users.each do |hello| %> to <% @users.each do |hello| %>.

Using <%= ... %> will output the result of the code inside it to the view. Since .each returns the array itself, using <%= ... %> with @users.each was causing the entire array of users to be printed. By using <% ... %>, we prevent Rails from trying to render the output of each and instead just iterate over the users as expected.

Upvotes: 1

Danylo Kravchenko
Danylo Kravchenko

Reputation: 11

Just replace

<%= @users.each do |hello| %>

by

<% @users.each do |hello| %>

Upvotes: 0

Jeroen Verfaillie
Jeroen Verfaillie

Reputation: 621

the <%= %> syntax (notice the =) executes ruby code and prints the result to your html.

This means that <%= @users.each do |hello| %> will, beside looping, also print the result of @users to your html file, which is the weird text you are seeing.

To solve this, simply change

<%= @users.each do |hello| %>

to

<% @users.each do |hello| %>

(so without = sign). This will still execute the ruby code, but not pass its return value to your html.

Upvotes: 0

Related Questions