Search code examples
ruby-on-railsrubyruby-on-rails-5backend

make an user with different courses and display it


I want to know if exists a way to create an user with differents course that are already registered in his account and show it with links in his page, like:

User {user_name}

courses:

• link_to course1

• link_to course2

• link_to course3


Solution

  • Assuming what you have

    class User < ApplicatonRecord
      has_many :courses
    end
    

    and in controller you assign @user var. You should have in view smth like that:

    <p> User: <%= @user.name %> </p>
    <ul>
    <% @user.courses do |course| %>
      <li><%= link_to(course.name, course) %></li>
    <% end %>
    </ul>