Не удалось найти пользователя без идентификатора ActiveRecord :: Запись не найдена - PullRequest
0 голосов
/ 27 января 2019

Поскольку я относительно новичок в rails, извиняюсь за несколько неосведомленный вопрос. В настоящее время я пытаюсь установить диспетчер задач с кликабельной ссылкой тега, при которой, когда вы нажимаете тег, он связывает его свсе задачи с тегом.Однако, поскольку я реализовал модель вложенных ресурсов для аутентификации пользователей и задач (статей), я понятия не имею, как изменить код так, чтобы он передавал параметры user_id в ссылку на тег.Любая помощь будет принята с благодарностью.Спасибо!

Это ошибка.

ActiveRecord::RecordNotFound in ArticlesController#index
Couldn't find User without an ID      
    # Confirms the correct user
    def correct_user
      @user = User.find(params[:user_id])
      redirect_to(root_url) unless current_user?(@user)
    end
end

Request
Parameters:

{"tag"=>"Hello"}

Routes.rb


Rails.application.routes.draw do
  get 'sessions/new'
  get 'welcome/index'
  get  '/signup',  to: 'users#new'
  post '/signup',  to: 'users#create'
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'

  resources :users do
      resources :articles 
  end
get 'tags/:tag', to: 'articles#index', as: :tag, :constraints  => { :tag => /[^\/]+/ }

  root 'welcome#index'
end

Schema.rb


ActiveRecord::Schema.define(version: 2019_01_27_035546) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "text"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.index ["user_id"], name: "index_articles_on_user_id"
  end

  create_table "taggings", force: :cascade do |t|
    t.bigint "tag_id"
    t.bigint "article_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["article_id"], name: "index_taggings_on_article_id"
    t.index ["tag_id"], name: "index_taggings_on_tag_id"

  end

  create_table "tags", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "password_digest"
    t.string "remember_digest"
    t.index ["email"], name: "index_users_on_email", unique: true
  end

  add_foreign_key "articles", "users"
  add_foreign_key "taggings", "articles"
  add_foreign_key "taggings", "tags"
end

Статьи Представления индекса

 <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= raw article.tags.map(&:name).map { |t| link_to t, tag_path(t) }.join(', ') %></td>
      <td><%= link_to 'Show', user_article_path(user_id: article.user.id, id: article.id) %></td>
      <td><%= link_to 'Edit', edit_user_article_path(user_id: article.user.id, id: article.id) %></td>
      <td><%= link_to 'Destroy', user_article_path(user_id: article.user.id, id: article.id),
              method: :delete,
              data: { confirm: 'Are you sure?' } %></td>

Контроллер сеансов

class SessionsController < ApplicationController

  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Log the user in and redirect to the user's show page.
      log_in user
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      redirect_back_or user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end
end

Помощник сеансов

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # Returns true if the given user is the current user.
  def current_user?(user)
    user == current_user
  end

  # Returns the current logged-in user (if any).
  def current_user
    if session[:user_id]
      @current_user ||= User.find_by(id: session[:user_id])
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end
  # Forgets a persistent session.
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    session.delete(:user_id)
    @current_user = nil
  end

    # Redirects to stored location (or to the default).
  def redirect_back_or(default)
    redirect_to(session[:forwarding_url] || default)
    session.delete(:forwarding_url)
  end

  # Stores the URL trying to be accessed.
  def store_location
    session[:forwarding_url] = request.original_url if request.get?
  end
end

Контроллер ARты

class ArticlesController < ApplicationController
  before_action :correct_user

  def index
      @user = User.find(params[:user_id])
      @articles = if params[:term]
       @user.articles.includes(:tags).where("articles.title LIKE :search OR tags.name LIKE :search", search: "%#{params[:term]}%" ).references(:tags)
        else
       @user.articles.all
  end
end
#    if params[:tag]
 #     @articles =  @user.articles.tagged_with(params[:tag])
 #   else
 #     @articles =  @user.articles.all
 #   end


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

def edit
      @user = User.find(params[:user_id])
  @article = @user.articles.find(params[:id])
end

def create
  @user = User.find(params[:user_id])
  @article = @user.articles.new(article_params)

  if @article.save
    redirect_to user_articles_url
  else
    render 'new'
  end
end

def update
   @user = User.find(params[:user_id])
  @article = @user.articles.find(params[:id])

  if @article.update(article_params)
    redirect_to user_articles_path
  else
    render 'edit'
  end
end

def destroy
  @user = User.find(params[:user_id])
  @article = @user.articles.find(params[:id])
  @article.destroy

  redirect_to user_articles_path
end
private
  def article_params
    params.require(:article).permit(:title, :text, :tag_list, :term)
  end


    # Confirms a logged_in user_
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "Please log in."
        redirect_to login_url
      end
    end

    # Confirms the correct user
    def correct_user
      @user = User.find(params[:user_id])
      redirect_to(root_url) unless current_user?(@user)
    end
end
...