简体   繁体   English

模型中的Rails协会“父母”参考

[英]Rails association “parent” reference in model

My following question might indicate a lack of proper understanding to how things really work in Ruby, Rails, or even general oOP concepts, and believe me i thought and searched a lot before asking, but i couldn't even form the correct search query to find the proper answer, so anyways here is what I would like to achieve ... 我的以下问题可能表明对Ruby,Rails或什至是通用的oOP概念的工作原理缺乏正确的理解,并相信我在询问之前进行了很多思考和搜索,但我什至无法形成正确的搜索查询来找到正确的答案,所以无论如何,这就是我想要实现的目标...

song = Artist.first.albums.first.songs.first 

this -to my understanding- will call the songs model and pass Artist model and Album model reference to the Song model to form an SQL query to fetch the data from the DB -since i am using ActiveRecord. 据我所知,这将调用歌曲模型,并将Artist模型和Album模型引用传递给Song模型,以形成一个SQL查询,以便从DB中获取数据,因为我正在使用ActiveRecord。

The real question; 真正的问题; is there a way to know which Artist and Album called the Song model? 有没有办法知道哪个歌手和专辑称为歌曲模型? this is useful specially in many-to-many relations where i don't want to pass an extra reference for the album/artist. 这在我不想传递专辑/艺术家的额外参考的多对多关系中特别有用。

So if I have a function in my model for whatever reason it will be able to tell who created this Song instance? 因此,如果出于某种原因我的模型中有一个函数,它将能够告诉谁创建了此Song实例?

That's too much chaining and it's overcomplicating things. 这太多了,而且使事情变得过于复杂。

However, you could do song.artist or song.album to retrieve the song's Artist and Album, supposing you have the belongs_to :album and belongs_to :artist relationships declared in your Song model. 但是,您可以执行song.artistsong.album来检索歌曲的艺术家和专辑,假设您在Song模型中声明了belongs_to :albumbelongs_to :artist关系。

However, you could simply do: 但是,您可以简单地执行以下操作:

artist = Artist.first
album = artist.albums.first
songs = album.songs

This way you have the Artist, his/her album you want (in this case the first one) and its songs all on different variables and you can handle them separately. 这样,您就拥有了Artist,想要的他/她的专辑(在本例中为第一张专辑)及其歌曲都在不同的变量上,并且可以分别处理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM