Твиттер клон - пытается показать имя пользователя рядом с их твитами в индексе твитов - devise - PullRequest
0 голосов
/ 28 сентября 2018

Я пытаюсь создать твиттер-клон.Я нахожусь в точке, где пользователь может опубликовать твит, и он показывает контент и время, когда он был опубликован.Однако я хочу, чтобы имя пользователя было рядом с твитом того, кто его написал.Я не уверен, как это сделать, так как ошибка в настоящее время «Не могу найти пользователя без идентификатора» в моем методе создания контроллера твита.Я также не уверен в синтаксисе для отображения имени пользователя в index.html.erb.спасибо.

class TweetsController < ApplicationController

  def index
    @tweets = Tweet.all.order("created_at DESC")
    @tweet = Tweet.new
    # @user = User.find(params[:id])
  end

  def show
    @tweet = Tweet.find(params[:id])
  end

  def new
    # @tweet = Tweet.new
  end

  def create
    @user = User.find(params[:id])
    @tweet = Tweet.new(tweet_params)
    @tweet.user = @user
    if @tweet.save
    redirect_to tweets_path
  end
  end

  def edit
    @tweet = Tweet.find(params[:id])
  end

  def update
    @tweet = Tweet.find(params[:id])
    @tweet.update(tweet_params)
    redirect_to tweets_path
  end

  private
  def tweet_params
    params.require(:tweet).permit(:user_id,:content)
  end
end

<h1>TWEETS</h1>

<%# @users.each do |user| %>
<%#= user.username %>
<%# end %>

<%= simple_form_for @tweet, id: "form-submit" do |f| %>
   <%= f.input :content, label: "Tweet" %>
   <%= f.button :submit, class: "btn btn-danger" %>
   <% end %>

   <br>

<% @tweets.each do |tweet|  %>
  <ul>
    <li>
      <%= tweet.created_at.strftime("%B %d %Y, %l:%M%P") %> <br>
      <%= tweet.content %>
      <%#= tweet.user.username %>
    <%#= tweet.user.username %>
    </li>
  </ul>
<% end %>

1 Ответ

0 голосов
/ 29 сентября 2018

Вам необходимо установить отношение между вашими пользователями и таблицей твитов

в вашей модели твитов добавить

 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

В сгенерированную миграцию.

enter image description here

...