質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

831閲覧

タグ機能実装でpost時にNoMethodError

sorata_toll

総合スコア19

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2020/12/31 08:58

編集2020/12/31 11:52

前提・実現したいこと

こちらを参考にタグ機能を実装していったところ、エラーが発生しました。

発生している問題・エラーメッセージ

ブラウザ上でtitleとcontentのみを入力した場合はpostは成功します。taglistに一文字でも入力するとエラーが出るといった感じです。また、何も入力しなくてもpostは成功します。

NoMethodError (undefined method `[]=' for nil:NilClass): app/controllers/posts_controller.rb:30:in `create' undefined method `[]=' for nil:NilClass

ソースコード

posts_controller.rb

ruby

1class PostsController < ApplicationController 2 before_action :set_post, only: [:show, :edit, :update, :destroy] 3 4 # GET /posts 5 # GET /posts.json 6 def index 7 @posts = Post.all 8 @tags = Post.tag_counts_on(:tags).most_used(20) 9 end 10 11 # GET /posts/1 12 # GET /posts/1.json 13 def show 14 @post = Post.find(params[:id]) 15 @tags = @post.tag_counts_on(:tags) 16 end 17 18 # GET /posts/new 19 def new 20 @post = Post.new 21 end 22 23 # GET /posts/1/edit 24 def edit 25 end 26 27 # POST /posts 28 # POST /posts.json 29 def create 30 @post = Post.new(post_params) 31 32 respond_to do |format| 33 if @post.save 34 format.html { redirect_to @post, notice: 'Post was successfully created.' } 35 format.json { render :show, status: :created, location: @post } 36 else 37 format.html { render :new } 38 format.json { render json: @post.errors, status: :unprocessable_entity } 39 end 40 end 41 end 42 43 # PATCH/PUT /posts/1 44 # PATCH/PUT /posts/1.json 45 def update 46 respond_to do |format| 47 if @post.update(post_params) 48 format.html { redirect_to @post, notice: 'Post was successfully updated.' } 49 format.json { render :show, status: :ok, location: @post } 50 else 51 format.html { render :edit } 52 format.json { render json: @post.errors, status: :unprocessable_entity } 53 end 54 end 55 end 56 57 # DELETE /posts/1 58 # DELETE /posts/1.json 59 def destroy 60 @post.destroy 61 respond_to do |format| 62 format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' } 63 format.json { head :no_content } 64 end 65 end 66 67 private 68 # Use callbacks to share common setup or constraints between actions. 69 def set_post 70 @post = Post.find(params[:id]) 71 end 72 73 # Only allow a list of trusted parameters through. 74 def post_params 75 params.require(:post).permit(:title, :content, :tag_list) 76 end 77end

post.rb

ruby

1class Post < ApplicationRecord 2 acts_as_taggable 3 acts_as_taggable_on :skills, :interests 4end

_form.html.erb

ruby

1<%= form_with(model: post) do |form| %> 2 <% if post.errors.any? %> 3 <div id="error_explanation"> 4 <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2> 5 6 <ul> 7 <% post.errors.each do |error| %> 8 <li><%= error.full_message %></li> 9 <% end %> 10 </ul> 11 </div> 12 <% end %> 13 14 <div class="field"> 15 <%= form.label :title %> 16 <%= form.text_field :title %> 17 </div> 18 19 <div class="field"> 20 <%= form.label :content %> 21 <%= form.text_area :content %> 22 </div> 23 24 <div class="field"> 25 <%= form.label :tag_list %> 26 <%= form.text_area :tag_list, value: @post.tag_list.join(',') %> 27 </div> 28 29 <% tag.each do |tag| %> 30 <%= form.check_box :tag_list, { multiple: true }, "#{tag.name}", nil %> 31 <%= form.label " #{tag.name}(#{tag.taggings_count})"%> 32 <% end %> 33 34 <div class="actions"> 35 <%= form.submit %> 36 </div> 37<% end %>

gemfile

ruby

1source 'https://rubygems.org' 2git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 4ruby '2.7.2' 5gem 'acts-as-taggable-on' 6 7# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 8gem 'rails', '~> 6.1.0' 9# Use sqlite3 as the database for Active Record 10gem 'sqlite3', '~> 1.4' 11# Use Puma as the app server 12gem 'puma', '~> 5.0' 13# Use SCSS for stylesheets 14gem 'sass-rails', '>= 6' 15# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker 16gem 'webpacker', '~> 5.0' 17# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks 18gem 'turbolinks', '~> 5' 19# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 20gem 'jbuilder', '~> 2.7' 21# Use Redis adapter to run Action Cable in production 22# gem 'redis', '~> 4.0' 23# Use Active Model has_secure_password 24# gem 'bcrypt', '~> 3.1.7' 25 26# Use Active Storage variant 27# gem 'image_processing', '~> 1.2' 28 29# Reduces boot times through caching; required in config/boot.rb 30gem 'bootsnap', '>= 1.4.4', require: false 31 32group :development, :test do 33 # Call 'byebug' anywhere in the code to stop execution and get a debugger console 34 gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 35end 36 37group :development do 38 # Access an interactive console on exception pages or by calling 'console' anywhere in the code. 39 gem 'web-console', '>= 4.1.0' 40 # Display performance information such as SQL time and flame graphs for each request in your browser. 41 # Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md 42 gem 'rack-mini-profiler', '~> 2.0' 43end 44 45group :test do 46 # Adds support for Capybara system testing and selenium driver 47 gem 'capybara', '>= 3.26' 48 gem 'selenium-webdriver' 49 # Easy installation and use of web drivers to run system tests with browsers 50 gem 'webdrivers' 51end 52 53# Windows does not include zoneinfo files, so bundle the tzinfo-data gem 54gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

試したこと

gemfileでバージョンを指定していないのが原因かと思い指定してみたところこのようなエラーが出てきたため戻しました。

gemfile

1gem 'acts-as-taggable-on', '~> 6.0'

console

1Fetching gem metadata from https://rubygems.org/............. 2Fetching gem metadata from https://rubygems.org/. 3Resolving dependencies... 4Bundler could not find compatible versions for gem "activerecord": 5 In snapshot (Gemfile.lock): 6 activerecord (= 6.1.0) 7 8 In Gemfile: 9acts-as-taggable-on (~> 6.0) x64-mingw32 was resolved to 6.0.0, which 10depends on 11 activerecord (~> 5.0) x64-mingw32 12 13 rails (~> 6.1.0) x64-mingw32 was resolved to 6.1.0, which depends on 14 activerecord (= 6.1.0) x64-mingw32 15 16Running `bundle update` will rebuild your snapshot from scratch, using only 17the gems in your Gemfile, which may resolve the conflict.

補足情報(FW/ツールのバージョンなど)

Windows10
ruby 2.7.2p137
Rails 6.1.0

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

app/controllers/posts_controller.rb:30:in `create'

この30行目とはどこのことになりますか?

おそらく、@postが空の場合の条件分岐が無いことが原因な気がしています。

投稿2020/12/31 10:52

educ_gt

総合スコア282

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

sorata_toll

2020/12/31 11:54 編集

@post = Post.new(post_params) こちらが30行目です。因みにブラウザ上でtitleとcontentのみを入力した場合はpostは成功します。taglistに一文字でも入力するとエラーが出るといった感じです。よろしくお願いします。
educ_gt

2020/12/31 12:45

binding.pryでparamsの中身をみるとどのような形になっていますか?
sorata_toll

2020/12/31 12:52

Started POST "/posts" for ::1 at 2020-12-31 21:51:31 +0900 Processing by PostsController#create as HTML Parameters: {"authenticity_token"=>"[FILTERED]", "post"=>{"title"=>"g", "content"=>"g", "tag_list"=>"g"}, "commit"=>"Create Post"} From: C:/Users/hoge/Desktop/blog8/app/controllers/posts_controller.rb:30 PostsController#create: 29: def create => 30: binding.pry 31: @post = Post.new(post_params) 32: 33: 34: respond_to do |format| 35: if @post.save 36: format.html { redirect_to @post, notice: 'Post was successfully created.' } 37: format.json { render :show, status: :created, location: @post } 38: else 39: format.html { render :new } 40: format.json { render json: @post.errors, status: :unprocessable_entity } 41: end 42: end 43: end [1] pry(#<PostsController>)> こちらでしょうか?
educ_gt

2020/12/31 13:02

ありがとうございます。 paramsには問題なさそうですね。 bundle list acts-as-taggable-on とするとどのような結果が出力されますか?
sorata_toll

2020/12/31 13:11

> bundle list acts-as-taggable-on ERROR: "bundle.cmd list" was called with arguments ["acts-as-taggable-on"] Usage: "bundle.cmd list" とでてきました
educ_gt

2020/12/31 13:16

なるほどです。なにかはねられてますね。。 アプリディレクトリでbundle list もエラーでますか?
sorata_toll

2020/12/31 13:28

> bundle list Gems included by the bundle: * actioncable (6.1.0) * actionmailbox (6.1.0) * actionmailer (6.1.0) * actionpack (6.1.0) * actiontext (6.1.0) * actionview (6.1.0) * activejob (6.1.0) * activemodel (6.1.0) * activerecord (6.1.0) * activestorage (6.1.0) * activesupport (6.1.0) * acts-as-taggable-on (5.0.0) * addressable (2.7.0) * bindex (0.8.1) * bootsnap (1.5.1) * builder (3.2.4) * byebug (11.1.3) * capybara (3.34.0) * childprocess (3.0.0) * coderay (1.1.3) * concurrent-ruby (1.1.7) * crass (1.0.6) * erubi (1.10.0) * ffi (1.14.2) * globalid (0.4.2) * i18n (1.8.5) * jbuilder (2.10.1) * loofah (2.8.0) * mail (2.7.1) * marcel (0.3.3) * method_source (1.0.0) * mimemagic (0.3.5) * mini_mime (1.0.2) * mini_portile2 (2.4.0) * minitest (5.14.2) * msgpack (1.3.3) * nio4r (2.5.4) * nokogiri (1.10.10) * pry (0.13.1) * pry-rails (0.3.9) * public_suffix (4.0.6) * puma (5.1.1) * rack (2.2.3) * rack-mini-profiler (2.3.0) * rack-proxy (0.6.5) * rack-test (1.1.0) * rails (6.1.0) * rails-dom-testing (2.0.3) * rails-html-sanitizer (1.3.0) * railties (6.1.0) * rake (13.0.3) * regexp_parser (1.8.2) * rubyzip (2.3.0) * sass-rails (6.0.0) * sassc (2.4.0) * sassc-rails (2.1.2) * selenium-webdriver (3.142.7) * semantic_range (2.3.1) * sprockets (4.0.2) * sprockets-rails (3.2.2) * sqlite3 (1.4.2) * thor (1.0.1) * tilt (2.0.10) * turbolinks (5.2.1) * turbolinks-source (5.2.0) * tzinfo (2.0.4) * tzinfo-data (1.2020.5) * web-console (4.1.0) * webdrivers (4.4.2) * webpacker (5.2.1) * websocket-driver (0.7.3) * websocket-extensions (0.1.5) * xpath (3.2.0) * zeitwerk (2.4.2) Use `bundle info` to print more detailed information about a gem 特にエラーはないかと思います
educ_gt

2020/12/31 13:33

acts-as-taggable-on (5.0.0) このバージョンが怪しそうなので、 gem 'acts-as-taggable-on', '~> 6.0'  を再度指定して、gemfile.lockを一度削除して、再度bundle installする。 だめなら gem 'acts-as-taggable-on', '~> 7.0' にして、再度gemfile.lockを削除してbundle install こちらでいかがでしょうか。
sorata_toll

2020/12/31 13:54

6の指定ではできませんでしたが、7を指定することで無事解決することができました! ありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問