Вам необходимо установить отношение между вашими пользователями и таблицей твитов
в вашей модели твитов добавить
class Tweet < ApplicationRecord
belongs_to :user
end
и в вашей пользовательской модели
class User < ApplicationRecord
has_many :tweets
end
rails g migration AddUserIdToMessages
и в этой миграции
def change
add_column :tweets, :user_id, :integer
end
После этого вы можете использовать <%= tweet.user.username %>
в своем представлении, чтобы показать имя пользователя
Мой тест: Контроллер
class TweetsController < ApplicationController
def index
@tweets = Tweet.all.order("created_at DESC")
end
end
Модель
class Tweet < ApplicationRecord
belongs_to :user
end
Просмотр (index.html.erb)
<% @tweets.each do |tweet| %>
<ul>
<li>
<%= tweet.created_at.strftime("%B %d %Y, %l:%M%P") %> <br>
<p> Content : <%= tweet.content %></p>
Username : <%= tweet.user.username %>
</li>
</ul>
<% end %>
Маршрут
Rails.application.routes.draw do
get 'tweet/index', to: 'tweets#index'
end
seed.rb (для тестирования)
User.create({username: "myName"})
Tweet.create({content: "hello",user_id: 1})
и run rake db:seed
и не забудьте добавить
def change
add_column :tweets, :user_id, :integer
end
В сгенерированную миграцию.