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

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

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

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

Ruby

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

Ruby on Rails

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

Q&A

解決済

2回答

1137閲覧

【Ruby on Rails】paramsでurlのidを取得できずnilになってしまいます...助けてください...

k_yusuke

総合スコア19

Ruby on Rails 5

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

Ruby

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

Ruby on Rails

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

0グッド

1クリップ

投稿2019/07/30 04:25

編集2019/07/30 10:29

前提・実現したいこと

rails tutorialの応用で記事(tourモデル)に対してコメントする機能を実装中です。
app/wiews/tours/show.html.hamlにコメントを反映させたいと考えています。
↓の記事を参考にしました
Railsでコメント機能をつくってみよう

問題点

comments_controllerのcreateアクションで、ページのurlからtour_idの値を取得したいのですが、
params[:tour_id]がnilになってしまい困っています。
エラー自体は出ていませんがコメントが反映されていない状況です。
ご教授お願いいたします。

試したこと

binding.pryをコメント保存後にかまして@commentの中身を見てみると、tour_idがnilになっていました。
app/wiews/tours/show/index.html.hamlのurlにはidが記載されてありました

該当のソースコード

app/db/schema

ruby

1ActiveRecord::Schema.define(version: 20190729131749) do 2 3 create_table "comments", force: :cascade do |t| 4 t.string "content" 5 t.integer "user_id" 6 t.integer "tour_id" 7 t.datetime "created_at", null: false 8 t.datetime "updated_at", null: false 9 t.index ["tour_id"], name: "index_comments_on_tour_id" 10 t.index ["user_id"], name: "index_comments_on_user_id" 11 end 12 13 create_table "tours", force: :cascade do |t| 14 t.string "tourname" 15 t.text "tourcontent" 16 t.integer "user_id" 17 t.datetime "created_at", null: false 18 t.datetime "updated_at", null: false 19 t.string "tour_image1" 20 t.string "tour_image2" 21 t.string "tour_image3" 22 t.index ["user_id", "created_at"], name: "index_tours_on_user_id_and_created_at" 23 t.index ["user_id"], name: "index_tours_on_user_id" 24 end 25 26 create_table "users", force: :cascade do |t| 27 t.string "email", default: "", null: false 28 t.string "encrypted_password", default: "", null: false 29 t.string "reset_password_token" 30 t.datetime "reset_password_sent_at" 31 t.datetime "remember_created_at" 32 t.datetime "created_at", null: false 33 t.datetime "updated_at", null: false 34 t.string "provider" 35 t.string "uid" 36 t.string "username" 37 t.boolean "admin_flg" 38 t.string "refresh_token" 39 t.string "access_token" 40 t.string "userimage" 41 t.index ["email"], name: "index_users_on_email", unique: true 42 t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 43 end 44 45end 46

app/medel/tour.rb

ruby

1class Tour < ApplicationRecord 2 3 belongs_to :user 4 has_many :likes 5 has_many :liked_users, through: :likes, source: :user 6 has_many :comments 7 8 mount_uploader :tourimage, ImagesUploader 9 validates :user_id,presence:true 10end

ruby

1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable,:omniauthable 6 7 8 has_many :tours, dependent: :destroy 9 has_many :likes, dependent: :destroy 10 has_many :liked_tours, through: :likes, source: :tour 11 mount_uploader :userimage, ImagesUploader 12 has_many :comments, dependent: :destroy 13end

app/medel/comment.rb

ruby

1class Comment < ApplicationRecord 2 belongs_to :user 3 belongs_to :tour 4 validates_uniqueness_of :tour_id, scope: :user_id 5 validates :user_id,presence:true 6 validates :tour_id,presence:true 7end 8

app/controller/comments_controller.rb

ruby

1class CommentsController < ApplicationController 2 def create 3 @comment = Comment.new(comment_params) 4 @comment.user_id = current_user.id 5 @comment.tour_id = params[:id] 6 binding.pry 7 if @comment.save 8 redirect_back(fallback_location: root_path) 9 else 10 redirect_back(fallback_location: root_path) 11 end 12 end 13 14 def destroy 15 @comment = Comment.find_by(user_id: current_user.id) 16 @comment.destroy 17 redirect_back(fallback_location: root_path) 18 end 19 20 private 21 22 def comment_params 23 params.require(:comment).permit(:content) 24 end 25 26end

app/controller/tours_controller.rb

ruby

1class ToursController < ApplicationController 2 3 def index 4 @tours=Tour.page(params[:page]).search(params[:search]) 5 end 6 7 def show 8 @tour=Tour.find_by(id: params[:id]) 9 @comments = Comment.where(tour_id: @tour.id) 10 @comment = Comment.new 11 end 12 13end 14

app/wiews/tours/show.html.haml

ruby

1%h1.page_title ツアー詳細 2.card 3 .card-body 4 %h4.card-title 5 %smallタイトル: 6 #{@tour.tourname} 7 %h6.card-subtitle.mb-2.text-muted 8 %small製作者: 9 #{@tour.user.username} 10 %p.card-text 11 = @tour.tourcontent 12 = image_tag @tour.tour_image1.to_s 13 = image_tag @tour.tour_image2.to_s 14 = image_tag @tour.tour_image3.to_s 15 // -if alredy_liked(@tour) 16 // = link_to('いいねを取り消す',like_path(@tour.id),method: :delete) 17 // -else 18 // = link_to('いいねする',likes_path(@tour.id),method: :post) 19.card 20 %h3.page_title コメント一覧 21 .card-body 22 -@comments.each do |comment| 23 %h6.card-subtitle.mb-2.text-muted 24 =comment.content 25 %h6.card-subtitle.mb-2.text-muted 26 ユーザー名: 27 =comment.user.username 28 %h6.card-subtitle.mb-2.text-muted 29 =comment.created_at 30 -if comment.user_id == current_user.id 31 = link_to("削除",comment_path(comment.id),class:"card-link",method: :delete) 32.card 33 .card-body 34 %h3.page_title コメントする 35 = simple_form_for(@comment) do |f| 36 = f.error_notification 37 .form-inputs.form_group 38 = f.input :content, 39 input_html: { autocomplete: "content",class:"form-control" } 40 =hidden_field_tag :tour_id,@tour.id 41 = f.button :submit, "Comment!", 42 input_html: { class:" btn btn-primary " }

app/wiews/tours/index.html.haml

ruby

1%h1.page_title tour一覧 2=render "shared/search" 3= page_entries_info @tours 4= paginate @tours 5-@tours.each do |tour| 6 .card 7 .card-body 8 %h4.card-title 9 %smallタイトル: 10 #{tour.tourname} 11 %h6.card-subtitle.mb-2.text-muted 12 %small製作者: 13 #{tour.user.username} 14 %p.card-text 15 = tour.tourcontent 16 = link_to "詳細",tour_path(tour.id),class:"card-link" 17= paginate @tours 18

app/config/routes.rb

ruby

1Rails.application.routes.draw do 2 3 4 mount RailsAdmin::Engine => '/admin', as: 'rails_admin' 5 root 'static_pages#home' 6 get '/about'=>'static_pages#about' 7 8 devise_for :users, controllers: { 9 registrations: 'users/registrations', 10 11 sessions: "users/sessions", 12 omniauth_callbacks: "users/omniauth_callbacks", 13 14 } 15resources :users, :only => [:show] 16resources :tours, :only => [:index,:new,:create,:show, 17 :edit,:update,:destroy] 18resources :likes, :only => [:create,:destroy] 19resources :comments, :only => [:create,:destroy] 20 21 # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 22end 23

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

Rails 5.0.7.2
cloud9使用

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

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

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

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

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

winterboum

2019/07/30 04:39

index.htmlに問題があると思うのですが、ここに示されている index.html はshow.htmlの様に思われます。indexを見せて下さい
k_yusuke

2019/07/30 05:10

回答ありがとうございます 申し訳ございません 質問のソースコードのパスに記載ミスがあったので訂正しました。 変更前 前提・実現したいこと app/wiews/tours/show/index.html.hamlにコメントを反映させたいと考えています。 ソースコード app/wiews/tours/show/index.html.haml 変更後 前提・実現したいこと app/wiews/tours/show.html.hamlにコメントを反映させたいと考えています。 ソースコード app/wiews/tours/show.html.haml
winterboum

2019/07/30 05:14

ツアーのindexからツアーの詳細に行くのが問題ではないのですね? Commentのnewへはどのviewから行くのか、がわからないのですがそれはどれ? Commentの new.htmlはどんな?
k_yusuke

2019/07/30 05:31

ツアーのindexからツアーの詳細に行くのは問題ありません! Commentのnewは用意せず、ツアー詳細ページにあるコメントフォームに入力することでCommentをcreate,destroyするように実装したいと考えています。 その際に、ツアー詳細ページのurlからtourのidをparamsで取得して、commentのtour_idに代入したいです!その際にparamsが空になるので困っています
guest

回答2

0

ベストアンサー

comment_path(comment.id)

comment_path(comment.id, tour_id: @tour.id)

Commentのnewは用意せず、,,,

これとても重要な情報です。
どこからどういうcodeによってこのcontrollerに来たのか、がないと判断間違えますから

間違えた、それ削除の所だからtour_id要らないですね。ちとまって

= f.input :content
の辺りに
= hidden_field_tag :tour_id,@tour.id
をいれて下さい

投稿2019/07/30 06:06

編集2019/07/30 06:11
winterboum

総合スコア23329

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

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

k_yusuke

2019/07/30 10:38

すみません、回答者の目線に立てていなかったです... winterboum様には回答のみならず、よりよい質問の仕方を教えていただき、本当に感謝しています。 指摘していただいた点を、ソースコードに反映してみました。 挿入する箇所はここで合っていますか?? やはり、まだコメントはツアー詳細ページ上に反映されていないようです。 comments_controller.rbのcreateアクション内でsave前の@tourの中身をbinding.pry覗くと ``` id: nil, content: "wdadawdaw", user_id: 122, tour_id: nil, created_at: nil, updated_at: nil> ```  と表示されます
winterboum

2019/07/30 10:46

comments_controller.rbのcreateアクション内には@tourって無いですが。 @comment ですか? 折角 tuor_id で渡してるのに、:id してるからです。 params を見て下さい @comment.tour_id = params[:id]
k_yusuke

2019/07/30 12:03

@comment.tour_id = params[:tour_id]としたところコメントが反映されました!!! 本当にありがとうございます!!すごく嬉しいです!!
guest

0

app/controller/tours_controller.rb

ruby

1 def show 2 @tour=Tour.find_by(id: params[:id]) 3 # @like=Like.new # 使ってないですよね?コレ 4 @comments = Comment.where(tour_id: @tour.id) 5 @comment = Comment.new(tour_id: @tour.id) 6 end

投稿2019/07/30 05:16

asm

総合スコア15147

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

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

k_yusuke

2019/07/30 10:39

回答ありがとうございます。 指摘していただいた箇所を変更してみたのですが、やはり、まだコメントはツアー詳細ページ上に反映されていないようです。別の個所に問題があるのでしょうか???
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問