неопределенный метод `user 'для # самоцвет - PullRequest
0 голосов
/ 14 июля 2020

Я использую gem devise для создания профиля пользователя. Каждый пользователь может оставить комментарий. Мне нужно показать только комментарии, отправленные пользователем, например: <% = @ comment.user.name%>, но я получил эту ошибку undefined method `user 'для #Comment: 0x007fee941c6aa8 gem devise

in user .rb

  has_many :comments, dependent: :destroy 

в comment.rb

  belongs_to :users
in comment controller

before_action :find_comment ,only:[:show,:update,:edit,:destroy]

   def new
    @user =User.find(params[:id])
    @comment = @user.comments.build
  end

  def create
    @user =User.find(params[:id])
    @comment = @user.comments.build(comment_params)
    @comment.user = current_user
    if @comment.save
      redirect_to doctor_path(:id => @user.id)
    end
  end

private

  def find_comment
    @comment = Comment.find(params[:id])
  end

  def comment_params
    params.require(:comment).permit(:text)
  end

пользовательский контроллер

      class DoctorsController < ApplicationController
  before_action :authenticate_user!
  before_action :find_user, only: [:destroy,:edit,:update]


  def index
    @users = User.order("id DESC").all
    
  end

  def show
    @user = User.find(params[:id])
    user_id = User.find(params[:id]).id

  @comments = Comment.where(user_id: user_id)
  current_user=@comments.where(user_id: user_id)
  end

  def edit
  end

  def update
    if @user.update_attributes(user_attributes)
      redirect_to members_path, notice: "user Information updated successfully"
    else
      flash.now[:error] = "Couldn't update!"
      render :edit
    end
  end

  private
  def user_attributes
    user_attributes = params.require(:user).permit([:name,:address,:phone])
  end
  def find_user
    @user = User.find(params[:id,:name])
  end
end

отображение пользователя. html .erb

<% for item in @user.comments %>
  <% if item.text.present? %>
    <%= item.text %><br>        
    <%= @comment.user.name %>
    <br><hr>
  <% end %>

база данных devis

# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :name
      t.string :phone
      t.string :address
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.inet     :current_sign_in_ip
      # t.inet     :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

в базе комментариев

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :text
      t.references :user, index: true, foreign_key: true
      
      t.timestamps null: false
    end
  end
end

1 Ответ

1 голос
/ 14 июля 2020

В вашем comment.rb это должно быть

belongs_to :user
...