ActsAsTaggableOn Undefined Method '[] =' for nil: NilClass - Создать действие

Заранее спасибо за помощь.

Ниже, в нижней части моего сообщения, я обновил его исправлением этой проблемы, отчасти благодаря Нарасимхе Редди. Надеюсь, это поможет любому, у кого возникнет аналогичная проблема после обновления до Rails 5.2. ОБНОВЛЕНИЕ: ActsAsTaggableOn 6.0 отсутствует и устраняет эту проблему.

Недавно я обновился до Rails 5.2, Ruby 2.5 и переключил свою базу данных разработки на PostgreSQL (9.3.18, gem: 1.0.0). Раньше этой проблемы не возникало, и с тех пор были внесены только вышеупомянутые изменения. Я использую гем ActsAsTaggableOn (5.0.0) для формы обзора, в которой используются два списка: love_list и Improve_list. Теперь при отправке формы я получаю следующую ошибку:

    NoMethodError in CityReviewsController#create
undefined method `[]=' for nil:NilClass Extracted source (around line 56)

 56:   @new_city_review = @city.city_reviews.build(city_review_params)
    @new_city_review.user_id = current_user.id  

Rails.root: /home/ubuntu/mvp1
Application Trace | Framework Trace | Full Trace
acts-as-taggable-on (5.0.0) lib/acts_as_taggable_on/taggable/core.rb:206:in `process_dirty_object'
acts-as-taggable-on (5.0.0) lib/acts_as_taggable_on/taggable/core.rb:184:in `set_tag_list_on'
acts-as-taggable-on (5.0.0) lib/acts_as_taggable_on/taggable/core.rb:45:in `love_list='
activemodel (5.2.0) lib/active_model/attribute_assignment.rb:51:in `public_send'
activemodel (5.2.0) lib/active_model/attribute_assignment.rb:51:in `_assign_attribute'
activemodel (5.2.0) lib/active_model/attribute_assignment.rb:44:in `block in _assign_attributes'
activemodel (5.2.0) lib/active_model/attribute_assignment.rb:43:in `each'
activemodel (5.2.0) lib/active_model/attribute_assignment.rb:43:in `_assign_attributes'
activerecord (5.2.0) lib/active_record/attribute_assignment.rb:23:in `_assign_attributes'
activemodel (5.2.0) lib/active_model/attribute_assignment.rb:35:in `assign_attributes'
activerecord (5.2.0) lib/active_record/core.rb:314:in `initialize'
activerecord (5.2.0) lib/active_record/inheritance.rb:66:in `new'
activerecord (5.2.0) lib/active_record/inheritance.rb:66:in `new'
activerecord (5.2.0) lib/active_record/reflection.rb:154:in `build_association'
activerecord (5.2.0) lib/active_record/associations/association.rb:270:in `build_record'
activerecord (5.2.0) lib/active_record/associations/collection_association.rb:106:in `build'
activerecord (5.2.0) lib/active_record/associations/collection_proxy.rb:319:in `build'
app/controllers/city_reviews_controller.rb:56:in `create'
actionpack (5.2.0) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (5.2.0) lib/abstract_controller/base.rb:194:in `process_action'
actionpack (5.2.0) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.2.0) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (5.2.0) lib/active_support/callbacks.rb:132:in `run_callbacks'
actionpack (5.2.0) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (5.2.0) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (5.2.0) lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
activesupport (5.2.0) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.0) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.0) lib/active_support/notifications.rb:168:in `instrument'
actionpack (5.2.0) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (5.2.0) lib/action_controller/metal/params_wrapper.rb:256:in `process_action'
activerecord (5.2.0) lib/active_record/railties/controller_runtime.rb:24:in `process_action'
actionpack (5.2.0) lib/abstract_controller/base.rb:134:in `process'
actionview (5.2.0) lib/action_view/rendering.rb:32:in `process'
actionpack (5.2.0) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (5.2.0) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:52:in `dispatch'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:34:in `serve'
actionpack (5.2.0) lib/action_dispatch/journey/router.rb:52:in `block in serve'
actionpack (5.2.0) lib/action_dispatch/journey/router.rb:35:in `each'
actionpack (5.2.0) lib/action_dispatch/journey/router.rb:35:in `serve'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:840:in `call'
omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!'
omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call'
warden (1.2.7) lib/warden/manager.rb:36:in `block in call'
warden (1.2.7) lib/warden/manager.rb:35:in `catch'
warden (1.2.7) lib/warden/manager.rb:35:in `call'
rack (2.0.5) lib/rack/tempfile_reaper.rb:15:in `call'
rack (2.0.5) lib/rack/etag.rb:25:in `call'
rack (2.0.5) lib/rack/conditional_get.rb:38:in `call'
rack (2.0.5) lib/rack/head.rb:12:in `call'
actionpack (5.2.0) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.0.5) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.5) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/cookies.rb:670:in `call'
activerecord (5.2.0) lib/active_record/migration.rb:559:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (5.2.0) lib/active_support/callbacks.rb:98:in `run_callbacks'
actionpack (5.2.0) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/executor.rb:14:in `call'
better_errors (2.4.0) lib/better_errors/middleware.rb:59:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call'
web-console (3.6.2) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.6.2) lib/web_console/middleware.rb:22:in `block in call'
web-console (3.6.2) lib/web_console/middleware.rb:20:in `catch'
web-console (3.6.2) lib/web_console/middleware.rb:20:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.0) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.0) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.0) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.0) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.0) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.0) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
request_store (1.4.1) lib/request_store/middleware.rb:19:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.5) lib/rack/method_override.rb:22:in `call'
rack (2.0.5) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.0) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.0) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.5) lib/rack/sendfile.rb:111:in `call'
railties (5.2.0) lib/rails/engine.rb:524:in `call'
puma (3.11.4) lib/puma/configuration.rb:225:in `call'
puma (3.11.4) lib/puma/server.rb:632:in `handle_request'
puma (3.11.4) lib/puma/server.rb:446:in `process_client'
puma (3.11.4) lib/puma/server.rb:306:in `block in run'
puma (3.11.4) lib/puma/thread_pool.rb:120:in `block in spawn_thread'
Request
Parameters:
{"utf8"=>"✓", "authenticity_token"=>"+KJueLU14yKJPxcTyhPbg0cQFkShT0oYjl9ddJR2pGKSDroJTReEMw7zukg3mpB5Gf3O8HhGYHDbYYqtNoM6Pw= = ",
 "city_review"=>
  {"title"=>"Blah Blah Blah",
   "score"=>"3",
   "love_list"=>"Schools / Education, Night Life, ",
   "improve_list"=>"Schools / Education, Taxes, ",
   "description"=>
    "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium.\r\n" +
    "Proin varius tincidunt purus, congue hendrerit ex interdum sed. Sed interdum, nibh ac lacinia vulputate, neque tellus ultricies nibh, eget vehicula ligula diam sit amet diam. Donec aliquam blandit laoreet. Cras at efficitur est. Phasellus quis enim vitae nisl sodales feugiat non sit amet tellus. Phasellus commodo, risus vitae luctus porta, nulla leo luctus massa, vel tempus odio tellus at nulla. Ut dictum nibh urna, quis scelerisque odio pellentesque ut. Sed at pretium nisi. Maecenas facilisis enim sed molestie gravida."},
 "commit"=>"Submit Review",
 "city_id"=>"lakewood"}

В моем серверном терминале появляется ошибка 500:

"Completed 500 Internal Server Error in 13ms (ActiveRecord: 1.5ms)"

В консоли Rails я получаю ту же ошибку. Мой контроллер размещен ниже:

class CityReviewsController < ApplicationController
# Main controller for City Reviews
  before_action :set_city_review, only: [:show, :edit, :update, :destroy, :upvote]
  # Below - Sets City for method actions of City Review.
  before_action :set_city, except: [:edit, :update, :destroy] 
  # Below - Multiples the score value that is initially 1 out of 5 and factors it by 20.
  before_action :multiply_score, only: [:create, :update]
  # Below - Sets user related params and IDs 
  before_action :set_user_params, only: [:edit, :update, :destroy]

  def show
    # Below - adds punch counter to City Review.
    @city_review.punch(request)
    @city_review_comments = @city_review.comments
  end

  # GET /city_reviews/new
  def new
    @new_city_review = CityReview.new
  end

  # GET /city_reviews/1/edit
  def edit
    # Calls all user related params and ids from a before action above.

  end

  def create
    # Below -  Creates a WUL City Review for the city using the "city_review_params" method in "private" below, passing
      # attributes for the :title, :score, :description, :city_review_score_id, :user_id, and :city_id, taggings list (:love_list, :improve_list) and assigning the Review to the city.
    @new_city_review = @city.city_reviews.build(city_review_params)
    # Below - Sets the user id to the current user posting the city review
    @new_city_review.user_id = current_user.id 
    # Below - Sets the City Review ID to the current users city's ID.
    @new_city_review.city_id = current_user.city.id
    # Below - Sets the City Review Score Id to the associated city id which should match the City Score ID column.
    @new_city_review.city_review_score_id = current_user.city.id
    # Begin - If statement for determining if the City Review was committed to the DB successfully, then rendering the City Reviews 
      # show page with a success message, or displaying an error and rendering a new form page.
    if @new_city_review.save # If it saves, display Flash message success, if not move to 'else'
      flash[:notice] = "Your What You Love review for #{@city.name} has been successfully posted!"   # Shows a Flash message of success
      redirect_to city_review_path(@city, @new_city_review)  # Redirects to the City Review's show page.
    else
      flash[:alert] = "Could not post your What You Love review for #{@city.name}. See why below!"   # Shows a Flash message of error
      render 'new' # Reload the New template with errors
    end # End - If statement for review creation.
  end

  def update
    # Calls all user related params and ids from a before action above.
    @city_review.user_id = current_user.id 
    # Below - Sets the City Review ID to the current users city's ID.
    @city_review.city_id = current_user.city.id
    # Below - Sets the City Review Score Id to the associated city id which should match the City Score ID column.
    @city_review.city_review_score_id = current_user.city.id

    if @city_review.update(city_review_params)
      flash[:notice] = "Your What You Love Review has been updated successfully!"
      redirect_to city_review_path(@city, @city_review)
    else 
      flash[:alert] = "Your What You Love Review could not be updated. See why below!"
      render 'edit'
    end 
  end

  def destroy
    # Calls all user related params and ids from a before action above.
    if @city_review.user === current_user
      if @city_review.destroy
        flash[:alert] = "Your What You Love review has been deleted."
        redirect_to city_review_index_path(@city)
      end
    end
  end

  private
    # Below - Finds the City Review ID from the params
    def set_city_review
      @city_review = CityReview.friendly.find(params[:id])
    end
    # Below - Sets up the city for City Review
    def set_city
      @city = City.friendly.find(params[:city_id])
    end

    def city_review_params
      params.require(:city_review).permit(:id, :title, :description, :score, :user_id, :city_id, :city_review_score_id, :love_list, :improve_list)
    end

    # Below - Sets up user related params on edit, update and destroy.
    def set_user_params 
      @user = User.friendly.find(params[:user_id])
      @city_review = CityReview.friendly.find(params[:id])
      @city = @city_review.city.friendly_id
      @city_review_edit = @city_review
    end 
    # Takes the user submitted Score value (1..1.5..) out of 5, empties the existing params (:score),
      # multiplies it by 20 to get a percentage value out of 100, and reassigns the params to the newly
        # multiplied value.
    def multiply_score
      user_score = params[:city_review].delete(:score).to_f
      score = user_score * 20
      params[:city_review][:score] = score
    end
end

Мой соответствующий код модели для ActsAsTaggableOn:

   acts_as_taggable_on :love, :improve

Я использовал, согласно предложению гема ActsAsTaggableOn, их настройку миграции, выполнив команду:

rake acts_as_taggable_on_engine:install:migrations

И вот как моя схема ищет эти таблицы:

 create_table "taggings", id: :serial, force: :cascade do |t|
    t.integer "tag_id"
    t.string "taggable_type"
    t.integer "taggable_id"
    t.string "tagger_type"
    t.integer "tagger_id"
    t.string "context", limit: 128
    t.datetime "created_at"
    t.index ["context"], name: "index_taggings_on_context"
    t.index ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
    t.index ["tag_id"], name: "index_taggings_on_tag_id"
    t.index ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
    t.index ["taggable_id", "taggable_type", "tagger_id", "context"], name: "taggings_idy"
    t.index ["taggable_id"], name: "index_taggings_on_taggable_id"
    t.index ["taggable_type"], name: "index_taggings_on_taggable_type"
    t.index ["tagger_id", "tagger_type"], name: "index_taggings_on_tagger_id_and_tagger_type"
    t.index ["tagger_id"], name: "index_taggings_on_tagger_id"
  end

  create_table "tags", id: :serial, force: :cascade do |t|
    t.string "name"
    t.integer "taggings_count", default: 0
    t.index ["name"], name: "index_tags_on_name", unique: true
  end

Пытаясь устранить это, я пробовал много разных вещей, таких как откат миграций, переустановка драгоценного камня, изменение имени списков, использование значения по умолчанию, использование его в другой модели и несколько различных действий контроллера. Кроме того, в коде вы также увидите наличие FriendlyID Gem.

Большое спасибо за чтение и вашу помощь.

* Чтобы временно исправить эту проблему с ActsAsTaggableOn в Rails 5.2, используйте ветку от Fodoj под названием rails-5.2. В вашем гем-файле добавьте ссылку и ветвь git на гем plays-as-taggable-on, а затем запустите установка пакета и перезапустите сервер: *

gem 'acts-as-taggable-on', :git => 'https://github.com/Fodoj/acts-as-taggable-on', :branch => 'rails-5.2'

Заглянул в это сегодня, спасибо, что разместили это. Сэкономил немного времени :)

Ben Scheirman 13.12.2018 16:09
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
3
1
603
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

На этом есть открытый проблема, а также открытый PR. Пожалуйста, рассмотрите эти вопросы

Вы можете использовать гем из этих веток (или) у вас может быть собственный форк с исправлением этой проблемы.

Спасибо, Нарашимха.

Twistedben 15.05.2018 18:17

Другие вопросы по теме