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

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

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

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

Ruby on Rails

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

Q&A

解決済

2回答

493閲覧

コメント機能を実装したい

taka3344

総合スコア8

Ruby

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

Ruby on Rails

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

0グッド

0クリップ

投稿2021/02/25 15:38

前提・実現したいこと

sellerとuserの両方が共通で使用できるコメント機能を作成しようと思っています。
しかし、現状エラーが出ることはないのですが、DBに保存されない状態が続いています。

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

[1] pry(#<CommentsController>)> @comment => #<Comment:0x00007f903e2680b0 id: nil, text: "kokokoko", user_id: 3, seller_id: nil, item_id: 2, created_at: nil, updated_at: nil> [2] pry(#<CommentsController>)> Comment.new(comment_params) => #<Comment:0x00007f903cdba320 id: nil, text: "kokokoko", user_id: 3, seller_id: nil, item_id: 2, created_at: nil, updated_at: nil> [3] pry(#<CommentsController>)> @comment.save (0.3ms) BEGIN ↳ (pry):3:in `create' Item Load (0.5ms) SELECT `items`.* FROM `items` WHERE `items`.`id` = 2 LIMIT 1 ↳ (pry):3:in `create' User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1 ↳ (pry):3:in `create' (0.5ms) ROLLBACK ↳ (pry):3:in `create' => false

該当のソースコード

commentsコントローラー
class CommentsController < ApplicationController def create @comment = Comment.new(comment_params) binding.pry if @comment.save redirect_to root_path else redirect_to item_path(@comment.item.id) end end private def comment_params params.require(:comment).permit(:text).merge(user_id: current_user&.id, seller_id: current_seller&.id, item_id: params[:item_id]) end end
commentモデル
class Comment < ApplicationRecord belongs_to :item belongs_to :user belongs_to :seller validates :text, presence: true end
items/マイグレーションファイル
create_table :comments do |t| t.text :text t.integer :user_id t.integer :seller_id t.references :item, null: false, foreign_key: true t.timestamps end
items/show.html.erb
<div class="comment-box"> <% if user_signed_in? || seller_signed_in? %> <%= form_with(model: [@item, @comment], local: true) do |form| %> <%= form.text_area :text, placeholder: "コメントする", rows: "2" %> <%= form.submit "SEND" %> <% end %> <% else %> <strong><p>※※※ コメントの投稿には新規登録/ログインが必要です ※※※</p></strong> <% end %> </div>
routes.rb
resources :items, except: :index do collection do get 'search' end resources :orders, only: [:index, :create] resources :favorites, only: [:create, :destroy] resources :comments, only: :create end
itemsコントローラー
class ItemsController < ApplicationController def index # items = Item.order('created_at DESC') items = Item.all if items.length < 8 @items = items.order('created_at DESC') else @items = Item.last(8).reverse end end def new @item = Item.new end def create @item = Item.new(item_params) if @item.save redirect_to root_path else render :new end end def show @item = Item.find(params[:id]) @comment = Comment.new @comments = @item.comments end end
sellerモデル
class Seller < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_one :address_seller has_many :items has_many :comments end
userモデル
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_one :address_user has_many :orders has_many :favorites, dependent: :destroy has_many :comments end
itemモデル
class Item < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :category belongs_to :state belongs_to :shopping_fee belongs_to :shopping_day belongs_to :area belongs_to :seller has_one :order has_one_attached :image has_many :favorites, dependent: :destroy has_many :comments

試したこと

binding.pryをしたところ、上記のエラー欄に書いた通り

[1] pry(#<CommentsController>)> @comment => #<Comment:0x00007f903e2680b0 id: nil, text: "kokokoko", user_id: 3, seller_id: nil, item_id: 2, created_at: nil, updated_at: nil> [2] pry(#<CommentsController>)> Comment.new(comment_params) => #<Comment:0x00007f903cdba320 id: nil, text: "kokokoko", user_id: 3, seller_id: nil, item_id: 2, created_at: nil, updated_at: nil> [3] pry(#<CommentsController>)> @comment.save (0.3ms) BEGIN ↳ (pry):3:in `create' Item Load (0.5ms) SELECT `items`.* FROM `items` WHERE `items`.`id` = 2 LIMIT 1 ↳ (pry):3:in `create' User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1 ↳ (pry):3:in `create' (0.5ms) ROLLBACK ↳ (pry):3:in `create' => false

とでてしまいました。
今回はsellerとuser共に使えるような仕様にしたため、seller_idかuser_idはnilになるようにしています。
初歩的なミスかもしれませんが、助言いただけると助かります。
よろしくお願いいたします。

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

ここにより詳細な情報を記載してください。

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

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

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

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

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

guest

回答2

0

ベストアンサー

belongs_to で指定した関連付けは、デフォルトだと必須です。
提示されている例だと、seller_id が nil なので必須バリデーションに引っかかり保存に失敗している状態です。

関連付けを必須にしたくない場合は、以下のように optional: true を指定します。

rb

1 belongs_to :user, optional: true 2 belongs_to :seller, optional: true

投稿2021/02/27 00:29

shinoharat2

総合スコア73

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

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

taka3344

2021/02/27 07:10

ありがとうございます。 こちらの方法で解決できました。 アソシエーションというものがデフォルトでnilの保存を弾いていることを忘れていました。
guest

0

@comment.saveの後、@comment.errors.full_messagesと打つと、どうなりますか?

そこに、ヒントがあるように思います。

投稿2021/02/25 17:02

yuyakanda

総合スコア17

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問