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

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

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

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

Ruby

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

Q&A

解決済

3回答

118閲覧

1:nの関係において、indexで最新のレコードのみ取得する方法

退会済みユーザー

退会済みユーザー

総合スコア0

Ruby on Rails 5

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

Ruby

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

0グッド

0クリップ

投稿2018/11/23 08:41

1:nのnでindexを表示しようと考えております。

表示内容はcreated_atなのですが、

index.html.erb

1 <% post.details.each do |detail| %> 2 <td><%= detail.updated_at %></td> 3 <% end%>

でレコード自体取得は問題なく出来ているのですが、n側にて例えば5つ更新を行っていると、5つ全てがindex.html.erbに表示されてしまいます。

最新のレコードのみを表示したいのですが、どうすれば良いでしょうか?

ご教示よろしくお願い致します。

index.html.erb

1 <% @posts.each do |post| %> 2 <tr> 3 <td><%= link_to post.company, post_path(post) %> </td> 4 <td><%= link_to post.owner, post_path(post) %></td> 5 <td><%= post.tel %></td> 6 <% post.details.each do |detail| %> 7 <td><%= detail.updated_at %></td> 8 <% end%> 9 <td><%= link_to '編集', edit_post_path(post), class: 'command'%> 10 <%= link_to '削除', 11 post_path(post), 12 method: :delete, 13 class: 'command', 14 data: { confirm: '本当に削除しますか?'} %></td> 15 <% end %> 16 </tr> 17 <tr> 18 <th colspan = "5"> 19 前のページ<%= paginate @posts %>次のページ 20 </th> 21 </tr> 22 </tbody> 23 </table>

イメージ説明

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

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

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

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

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

guest

回答3

0

イメージ説明

投稿2018/11/24 11:10

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

0

post.rb

1# == Schema Information 2# 3# Table name: posts 4# 5# id :integer not null, primary key 6# company :string 7# owner :string 8# tel :string 9# address :string 10# people :string 11# status :string 12# datetime :string 13# comment :string 14# created_at :datetime not null 15# updated_at :datetime not null 16# 17 18class Post < ApplicationRecord 19 has_many :details 20 21 22 23 def self.import(file) 24 CSV.foreach(file.path, headers: true) do |row| 25 # IDが見つかれば、レコードを呼び出し、見つかれなければ、新しく作成 26 post = find_by(id: row["id"]) || new 27 # CSVからデータを取得し、設定する 28 post.attributes = row.to_hash.slice(*updatable_attributes) 29 # 保存する 30 post.save! 31 end 32 end 33 34 35 def self.updatable_attributes 36 ["company", "store", "owner","kana", "tel", "tel2","fax", "industry" "address", "mail" , "url ", "people"] 37 end 38 39 40 def self.search(search) #self.でクラスメソッドとしている 41 if search # Controllerから渡されたパラメータが!= nilの場合は、titleカラムを部分一致検索 42 Post.where( 43 ['company LIKE ?', "%#{company}%"], 44 ['store LIKE ?', "%#{store}%"], 45 ['owner LIKE ?', "%#{owner}%"], 46 ['kana LIKE ?', "%#{kana}%"], 47 ['tel LIKE ?', "%#{tel}%"], 48 ['tel2 LIKE ?', "%#{tel2}%"], 49 ['fax LIKE ?', "%#{fax}%"], 50 ['industry LIKE ?', "%#{industry}%"], 51 ['mail LIKE ?', "%#{mail}%"], 52 ['url LIKE ?', "%#{url}%"], 53 ['people LIKE ?', "%#{people}%"], 54 ['address LIKE ?', "%#{address}%"], 55 ['statu LIKE ?', "%#{statu}%"], 56 ['time LIKE ?', "%#{time}%"], 57 ['comment LIKE ?', "%#{comment}%"], 58 ['created_at BETWEEN ? AND ?', from, to, "%#{created_at}%"], 59 ) 60 61 else 62 Post.all #全て表示。 63 end 64 end 65 66 def next_post 67 Post.where("id > ?", id).first 68 end 69 70 def prev_post 71 Post.where("id < ?", id).last 72 end 73end

schema.rb

1# This file is auto-generated from the current state of the database. Instead 2# of editing this file, please use the migrations feature of Active Record to 3# incrementally modify your database, and then regenerate this schema definition. 4# 5# Note that this schema.rb definition is the authoritative source for your 6# database schema. If you need to create the application database on another 7# system, you should be using db:schema:load, not running all the migrations 8# from scratch. The latter is a flawed and unsustainable approach (the more migrations 9# you'll amass, the slower it'll run and the greater likelihood for issues). 10# 11# It's strongly recommended that you check this file into your version control system. 12 13ActiveRecord::Schema.define(version: 2018_11_22_055616) do 14 15 create_table "comments", force: :cascade do |t| 16 t.string "responsible" 17 t.string "product" 18 t.string "statu" 19 t.datetime "time" 20 t.string "detail" 21 t.integer "sfa_id" 22 t.datetime "created_at", null: false 23 t.datetime "updated_at", null: false 24 t.index ["sfa_id"], name: "index_comments_on_sfa_id" 25 end 26 27 create_table "details", force: :cascade do |t| 28 t.string "statu" 29 t.datetime "time" 30 t.string "comment" 31 t.integer "post_id" 32 t.datetime "created_at", null: false 33 t.datetime "updated_at", null: false 34 t.index ["post_id"], name: "index_details_on_post_id" 35 end 36 37 create_table "posts", force: :cascade do |t| 38 t.string "company" 39 t.string "store" 40 t.string "owner" 41 t.string "kana" 42 t.string "tel" 43 t.string "tel2" 44 t.string "fax" 45 t.string "industry" 46 t.string "mail" 47 t.string "url" 48 t.string "people" 49 t.string "address" 50 t.datetime "created_at", null: false 51 t.datetime "updated_at", null: false 52 end 53 54 create_table "sfas", force: :cascade do |t| 55 t.string "company" 56 t.string "store" 57 t.string "owner" 58 t.string "kana" 59 t.string "person" 60 t.string "p_kana" 61 t.string "tel" 62 t.string "tel2" 63 t.string "fax" 64 t.string "industry" 65 t.string "mail" 66 t.string "url" 67 t.string "people" 68 t.string "post_number" 69 t.string "address" 70 t.string "employment" 71 t.string "social" 72 t.string "appointer" 73 t.string "sales_staff" 74 t.string "sales_day" 75 t.string "status" 76 t.string "target" 77 t.string "sales_forecast" 78 t.string "impression" 79 t.string "repeat_sales" 80 t.string "next_sales" 81 t.string "prospect" 82 t.string "ditails" 83 t.string "examination" 84 t.datetime "created_at", null: false 85 t.datetime "updated_at", null: false 86 end 87 88 create_table "users", force: :cascade do |t| 89 t.string "email", default: "", null: false 90 t.string "encrypted_password", default: "", null: false 91 t.string "reset_password_token" 92 t.datetime "reset_password_sent_at" 93 t.datetime "remember_created_at" 94 t.integer "sign_in_count", default: 0, null: false 95 t.datetime "current_sign_in_at" 96 t.datetime "last_sign_in_at" 97 t.string "current_sign_in_ip" 98 t.string "last_sign_in_ip" 99 t.datetime "created_at", null: false 100 t.datetime "updated_at", null: false 101 t.index ["email"], name: "index_users_on_email", unique: true 102 t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 103 end 104 105end 106

投稿2018/11/24 11:05

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

0

ベストアンサー

<% post.details.each do |detail| %> <td><%= detail.updated_at %></td> <% end %>

<td><%= post.details.order('updated_at DESC').first.updated_at %></td>

とすれば、関連テーブル先の更新された最新データ一件についての更新日時を取得できると思います。

投稿2018/11/23 10:50

troch

総合スコア349

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

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

退会済みユーザー

退会済みユーザー

2018/11/24 08:22

ありがとう御座います。 上記だと、エラーが発生してしまうようです。 controller設定等が必要なのでしょうか?
退会済みユーザー

退会済みユーザー

2018/11/24 08:24

<% post.details.each do |detail| %> <td><%= post.details.order('updated_at DESC').first.updated_at %></td> <% end %> 上記の場合、エラーは発生せずに表示出来ますが、当初の写真通り、updatedの全てが表示されてしまいます・
troch

2018/11/24 08:44

↑で一応、出力されるのに、 <td><%= post.details.order('updated_at DESC').first.updated_at %></td> だとエラーになる、というのは変ですね…。 エラー文を見せていただけますでしょうか?
troch

2018/11/24 08:46

それから、app/models/post.rbと、db/schema.rbの内容も見せていただけませんでしょうか。
退会済みユーザー

退会済みユーザー

2018/11/24 11:11

ご確認よろしくお願い致します。
troch

2018/11/24 11:47

エラー画像 確認しました。 post.detailsで取得した値がnilなのでエラーになっているのかもしれません… 確認なのですが、すべてのpostは必ずdetailsレコードを持つのでしょうか? detailsを持たないpostもあるのでしょうか? KentaOkuyamaさんが質問欄にアップしてくださいました当初の写真を見ますと、最終更新日の列にデータが入っておらず、[編集 削除] ボタンが入っている行もありますが… (つまりその行はdetailsを持たないpostなのではないでしょうか?)
troch

2018/11/24 11:51

・detailsを持たないpostレコードもある ・その場合、空白の列として表示できればいい という条件でいいのであれば、 <td><%= post.details.order('updated_at DESC').first.try(:updated_at) %></td> のコードに書き換えればおそらく動くと思います。
退会済みユーザー

退会済みユーザー

2018/11/25 10:29

ありがとう御座います。解決しました。もっと自分で勉強してみます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問