Rails has_and_belongs_to_many 让我对装置和工厂感到困惑
普遍混乱
我的乐队可以有 3 种风格。 我在上一篇文章中读到,正确的处理这个问题的方法有几个步骤:
1)在 band.rb 中
has_and_belongs_to_many :genres
2)创建 band_genres 连接表
即使在阅读文档之后,我对 HABTM 的实际含义还是有点困惑。 我想我通常会认为“一个乐队有很多流派”,而不是拥有并属于很多流派。 因此,对此进行快速简化的解释会很棒。
与固定装置的混淆
另外,当我为 band_genres 进行固定装置时,
{
"The Reaper Band and Funk": { "band": "The Reaper Band", "genre": "Funk" },
"The Reaper Band and Rock": { "band": "The Reaper Band", "genre": "Rock" }
}
我得到了一个“未知”的乐队列。 我认为 Rails 应该知道“The Reaper Band”将引用乐队固定装置中的乐队(当然名称相同),并且会获取该 id 并知道该固定装置中的“乐队”将引用连接表中的 band_id 。 我宁愿我的灯具看起来像这样,也不愿有硬编码的数字。
与工厂的混淆
当我在工厂中创建乐队时,我想为其分配流派:
Factory.define :band do |f|
f.sequence(:name) { |n| "Band#{n}" }
f.mailing_lists { |mailing_lists| [mailing_lists.association(:mailing_list)] }
f.genres 2
end
我意识到这里我可能需要一个硬编码的genre_id。 但为什么 Rails 不看看并说“哦,他想将 id=2 的流派添加到 band_genres 表中”。
我并不期望 Rails 为我处理所有肮脏的工作,但我确实想遵守规则。
General Confusion
I have bands which can have 3 genres. I read in a previous SO post that the proper way to handle this is a couple steps:
1) In band.rb
has_and_belongs_to_many :genres
2) Create a band_genres join table
Even after reading the documentation, I am a bit confused as to what HABTM actually means. I guess I would just normally think "a band has many genres", not has and belongs to many. So a quick DUMBED down explanation of that would be great.
Confusion with Fixtures
Also, when doing my fixture for band_genres I have
{
"The Reaper Band and Funk": { "band": "The Reaper Band", "genre": "Funk" },
"The Reaper Band and Rock": { "band": "The Reaper Band", "genre": "Rock" }
}
And I get a "unknown" band column. I thought rails was supposed to know that "The Reaper Band" would refer to a band from a band fixture (same name of course) and would grab that id and know that "band" in this fixture would refer to band_id in the join table. I would rather my fixtures look like this than have hard coded numbers.
Confusion With Factories
When I create a band in my factory, I want to assign it genres:
Factory.define :band do |f|
f.sequence(:name) { |n| "Band#{n}" }
f.mailing_lists { |mailing_lists| [mailing_lists.association(:mailing_list)] }
f.genres 2
end
I realize here I would probably need a hard coded genre_id. But why doesn't rails look at that and say "oh, he wants to add genre with id=2 to the band_genres table".
I am not expecting rails to take care of all the dirty work for me, but I do want to play by the rules.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在bands.yml中:
在genres.yml中:
in bands.yml:
in genres.yml: