Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4

How can I display values from relationship on column array?


I have 2 tables (users and meetings).

I'm trying to displaying the name of the user on table index view

users
 |id|   |name|
  1      DEMO 1
  2      DEMO 2
  3      DEMO 3

meetings
 |id|    |user_id|
  1      ["1", "2"]
  2      ["2"]
  3      ["2", "3"]

The Controller /app/controllers/meetings_controller.erb

def index
  @meetings = Meeting.all
end

Models

#meeting.rb
class Meeting < ApplicationRecord
  belongs_to :users
end

#user.rb
class User < ApplicationRecord
 has_many :meetings
end

The View /app/views/meetings/index.html.erb

<table>
 <thead>
   <tr>
      <td>id</td>
      <td>User Names</td>
   </tr>
 </thead> 
 <tbody>
   <% @meetings.each do |meeting| %>
   <tr>
      <td><%= meeting.id %></td>
      <td><%= meeting.user_id %></td>
   </tr>
   <% end %>
 </tbody>
</table>

I'm trying to display the user_id on array relationship and i tried this code:

I got the following error using the following code

 undefined method `each' for "[\"1\", \"2\"]":String

 <% meeting.user_id do |array|%>
   <%= array.user.name %>
 <% end %>

I got the following error using the following code

 undefined method `each' for "[\"1\", \"2\"]":String

 <% meeting.user_id do |array|%>
   <%= array %>
 <% end %>

I cannot display the value relationship because of column array.

Can you please help me with this issue?

Thanks in advance.


Solution

  • While there is nothing wrong with your approach, one comes to understand that the path of least resistance (= least pain) is to follow "The Rails Way".

    So instead of answering your question, let me suggest that the relationship between your models should be:

    # user.rb
    class User < ActiveRecord::Base
      has_and_belongs_to_many :meetings
    end
    
    # meeting.rb
    class Meeting < ActiveRecord::Base
      has_and_belongs_to_many :users
    end
    
    # you will also need to create a join table with a migration:
    def change
     create_join_table :meetings, :users
    end
    

    Then the view will include:

       <% @meetings.each do |meeting| %>
       <tr>
          <td><%= meeting.id %></td>
          <td><%= meeting.users.map(&:name).join(', ') %></td>
       </tr>
       <% end %>