Organize an association so that there is a many-to-many relationship How to get information on the associated table.
Language: Ruby Take the app I'm working on as an example. I made a many-to-many association between the CD and the songs on it. Many-to-many reason: The CD contains multiple songs. The song may be on multiple CDs.
So Create a one-to-many table. An intermediate table is also created at the same time.
Based on this discs table Viwe (show.haml.html) is prepared because I want to make a detailed page of each CD.
(URL▶︎localhost:3000/discs/1)
Example ①: When disc_id is 1
Information you want to get / display: Songs associated with CD-A (song-A, song-B, song-C)
Example ②: When disc_id is 2
Information you want to get / display: Songs linked to CD-B (song-A, song-D, song-E)
: point_right_tone1: I want to get information from related tables as well! That is the goal this time.
If the related pink song title is also displayed on the same page, it is successful. Did you understand what you wanted to do?
Here, we will get the id displayed in the URL. For example, disc_id: 1. The user can instruct that he wants the information on the id: 1 CD.
discs_controller.rb
class DiscsController < ApplicationController
#abridgement
def show
@disc = Disc.find(params[:id])
end
#abridgement
end
ruby:show.html.haml(show.html.For erb, convert haml to html. )
- @disc.songs.each do |song|
= song.name
For routing, I put: show like "resources: discs, only: [: show]".
I think the point is the description when straddling the table.
ruby:show.html.haml(show.html.For erb, convert haml to html. )
- (params[:id]Variable).(Related table name you want to earn).each do |(Variables used below)|
=(Variables specified above).(The column name you want to display in the income table)
I thought the explanation was crap, but I wrote it in detail.
I think I was able to display it above. Thank you for your hard work!
I'm honestly really a beginner Currently, the merits of forming an association, Understanding of the merits of having a parent-child relationship has not caught up. However, this time, I found that by making many-to-many, other table information can be fetched even in the view linked to a single table. I noticed that the information from the URL that can be received from the client comes from "/ discs / 1", "/ discs / 1 / song", "discs / new", and so on. Also, in routing, I just noticed that I received instructions from the main information source table, received the displayed viwe information, and could describe the information fetched from the table with the controller.
If someone who is similarly worried about the basics can get some hints with this, It should make sense for me to stumble here! I thought I recorded it here as an article for myself who will stumble in the same place again in the future. Thank you for reading to the end: relaxed: See you again: wave:
Recommended Posts