Home > database >  render methods display text of full ActiveRecord relation object Rails 7
render methods display text of full ActiveRecord relation object Rails 7

Time:09-22

I have a model that have relations many to many with 3 other models

Models

class User < ApplicationRecord

  # == Relationships ==============================================================================

  has_and_belongs_to_many :hobbies, join_table: 'hobbies_users'
  has_and_belongs_to_many :jobs, join_table: 'jobs_users'
  has_and_belongs_to_many :degrees, join_table: 'degrees_users'


end
class Degree < ApplicationRecord

  has_and_belongs_to_many :users, join_table: 'degrees_users'

end

the other models looks the same.

I also have a controller for the user with his index method

Controller

class UsersController < ApplicationController

  def index
    @users = User.all
  end

end

View

In the view I want to render every User within a Card "Shared" layout.

<h1>Usuarios</h1>

<div >
<%= @users.each do |user| %>
  <%= render "card", user: user %>
<% end %>
</div>

Shared card

it's a card from a template.

<div >
    <div >
        <div >
            <p><%= image_tag "https://images.pexels.com/photos/10474224/pexels-photo-10474224.jpeg?cs=srgb&dl=pexels-rodnae-productions-10474224.jpg&fm=jpg", class: "img-fluid" %></p>
            <h4 > <%= user.name %></h4>
            <p ><%= user.description %></p>
            <a href="https://www.fiverr.com/share/qb8D02" ><i ></i></a>
        </div>
    </div>
</div>

On localhost browser

when I look the index of user in local host, it renders de cards for every user, but at the end it renders the ActiveRecord array at the bottom as plain text.

I don't understand why.

Here's a screen shoot of what I'm saying. I don't know how to get rid of it

Screen Shoot

CodePudding user response:

Just remove the = from the line in which you iterate all users and change it to this:

<% @users.each do |user| %>
  <%= render "card", user: user %>
<% end %>

A <%= in ERB indicates that your want to output the result of the following statement. This is what you want with each <%= render "card", user: user %> because those lines return rendered HTML.

But <% @users.each do |user| %> is only used to iterate all users, you do not want to output the response of the @users.each call which is only a string representation of an Enumerator

  • Related