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

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

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

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

Q&A

解決済

1回答

1229閲覧

form_forで投稿した内容が表示されない

退会済みユーザー

退会済みユーザー

総合スコア0

Ruby on Rails

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

0グッド

1クリップ

投稿2019/11/16 16:21

編集2019/11/21 13:24

本の投稿ができるアプリを作成しています。
自分の投稿が一覧で表示させたいのですが、データがうまく保存できていないのか表示されず同じページが表示されてしまいます。
エラーは特に出ておりません。
ご確認頂ければと思います。

show.html.erb

<%= render 'shared/header' %> <div class="top"> <div class="container"> <div class="row"> <div class="col-lg-3"> <p>User info</p> <%= attachment_image_tag @user, :profile_image_id, :fill, 250, 250, format: 'jpeg', fallback: "no_image.jpg", size:'250x250' %> <table class="table"> <tr>    <th>name</th>    <th><%= current_user.name %></th>   </tr>   <tr>    <th>introduction</th>    <th><%= current_user.introduction %></th>    </tr> </table> <%= link_to edit_user_path, class: "btn btn-default" do %> <i class="fa fa-wrench"></i> <% end %> <p>New book</p>    #ここから投稿欄 <%= form_for(@book, url: '/users') do |f| %> <p>Title</p> <%= f.text_field :title %> <p>Opinion</p> <%= f.text_area :body %> <%= f.submit 'Create Book' %> <% end %> #ここまで </div> <div class="col-lg-9"> <p>Books</p> <table class="table table-hover"> <thead> <tr> <th></th> <th>Title</th> <th>Opinion</th> </tr> </thead> #ここから投稿一覧 <% @books.each do |book| %> <tbody> <tr> <td>名前、写真</td> <td><%= book.title %></td> <td><%= book.body %></td> </tr> </tbody> <% end %> #ここまで </table> </div> </div> </div> </div> <%= render 'shared/footer' %>

20191003161330_create_books.rb

class CreateBooks < ActiveRecord::Migration[5.0] def change create_table :books do |t| t.string :title t.text :body t.integer :user_id t.timestamps end end end

users_controller.rb

class UsersController < ApplicationController def index @user = current_user @users = User.all @book = Book.new end def show @user = User.find(params[:id]) @book = Book.new @books = @user.books end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) user.update(user_params) redirect_to user_path(@user) end private def user_params params.require(:user).permit(:name, :introduction, :profile_image_id) end end

books_controller.rb

class BooksController < ApplicationController before_action :authenticate_user!, only: [:show] def create book = Book.new(book_params) book.user = current_user book.save redirect_to '/books/:id' end def index end def show @book = Book.find(params[:id]) end def edit @book = Book.find(params[:id]) end def update @book = Book.find(params[:id]) book.update(book_params) redirect_to user_path(@user) end private def book_params params.require(:book).permit(:title, :body) end end

user.rb

class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :books, dependent: :destroy attachment :profile_image end

book.rb

class Book < ApplicationRecord belongs_to :user end

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

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

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

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

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

NCC1701

2019/11/18 02:25

books_controller.rbが掲載されてません。ので、原因はわかりません。 ついでに掲載されているusers_controller.rbを読むと、Userのデータ自体保存されないように見受けられます。
guest

回答1

0

ベストアンサー

おそらく、関連付け(association)の保存がうまくできてないか、そもそも関連付けの設定がうまくいっていないからと思われます。
books_controller.rb のこの部分を読むと

rails

1def create 2 book = Book.new(book_params) 3 book.save 4 redirect_to '/books/:id' 5end

bookは保存されてます。しかし、user.books << bookなどいくつかの方法があるところ、Userとの関係を設定する行が一切ありませんでした。
なので、users_controller.rbで

rails

1def show 2 @user = User.find(params[:id]) 3 @book = Book.new 4 @books = @user.books 5end

@user.booksからbooksを取り出そうとしても、そもそもデータが「空」(nil)です。

[初心者向け] Railsで関連するデータ(親子関係)を保存する方法あれこれ
このあたりを参考に設計し直してみてください。

投稿2019/11/18 13:03

NCC1701

総合スコア1680

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

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

退会済みユーザー

退会済みユーザー

2019/11/18 14:35

ご回答頂きありがとうございます。 関連付けはモデルの方でやっておりました。 追記をしましたので、ご確認頂ければと思います。
NCC1701

2019/11/22 11:26

エラーになりませんか?データの保存以前に、そもそもlocalhost:3000/usersでエラーになるはずです。
退会済みユーザー

退会済みユーザー

2019/11/22 12:37

エラーは発生しておりません。 引き続き投稿されない状態が続いております。
NCC1701

2019/11/24 12:15

こちらではエラーになってしまし、そちらの状況を再現できません。エラーメッセージもなく、再現もできないと、対処法はわかりません。
退会済みユーザー

退会済みユーザー

2019/11/24 13:28

rails c でBook.allやBook.find(1)を試してみましたが、そこから分かることがあるでしょうか? 2.6.3 :001 > Book.all Book Load (1.6ms) SELECT "books".* FROM "books" => #<ActiveRecord::Relation []> 2.6.3 :001 > Book.find(1) Book Load (0.1ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] Traceback (most recent call last): 16: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:287:in `load' 15: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:259:in `load_dependency' 14: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:287:in `block in load' 13: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:287:in `load' 12: from /home/ec2-user/environment/bookers-level2.herokuapp/bin/rails:9:in `<top (required)>' 11: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:293:in `require' 10: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:259:in `load_dependency' 9: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:293:in `block in require' 8: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activesupport-5.0.7.2/lib/active_support/dependencies.rb:293:in `require' 7: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/railties-5.0.7.2/lib/rails/commands.rb:18:in `<top (required)>'
NCC1701

2019/11/25 10:39

Book.allの結果、データは空ですね。なので一覧にも出ません。User.allでもデータは空ではないでしょうか?
退会済みユーザー

退会済みユーザー

2019/11/25 11:56

User.allの方では名前やid等が登録されているようです。 2.6.3 :001 > User.all User Load (1.8ms) SELECT "users".* FROM "users" => #<ActiveRecord::Relation [#<User id: 1, email: "メールアドレス", created_at: "2019-11-15 16:43:22", updated_at: "2019-11-15 16:43:22", name: "登録名", introduction: nil, profile_image_id: nil>, #<User id: 2、、、、
NCC1701

2019/11/25 14:23

質問の「自分の投稿が一覧で表示させたいのですが、」の結論です。 当たり前ですが、そもそもBookデータが無い以上表示させるものがないので、表示されていないということです。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問