问题描述
刚开始在轨并试图重构了一点我的看法,我有点难倒到哪儿去寻找答案,因为我内的每一个循环,我需要访问|项目|
Just getting started in rails and trying to refactor down a bit of my view, and I'm a bit stumped as to where to go for the answer since I'm inside an each loop I need access to the |item|.
我是从一个CSV文件拉动作家,用创作者表和书籍HABTM ASSOCATION。原因是有时笔者也插画,也是编辑,我不想3(更可能)一书的作者的每个特定角色的表。
I'm pulling the writer from a CSV file, using a creator table and a HABTM assocation with books. The reason is sometimes the writer is also the illustrator and also the editor, I didn't want 3 (and more maybe) tables for each specific role of a book author.
书籍模型(以CSV导入)
Books Model ( with CSV import )
writer = Creator.where(name: row['writer']).first_or_create!(row.to_hash.slice(:writer))
book.creators << writer
book.writer_id = writer.id
图书查看
books.each do |book|
link_to book.creators.detect{|w| w.id == book.writer_id}.name, creator_path(id: book.writer_id)
然后我重复,对于艺术家,编辑,等等...
And then I duplicate that for artist, editor, etc...
我第一次尝试在控制器中@books,但我需要知道哪本书从循环。我不知道下一步要了解这样我就可以去除难看。我见过很多事情我想继续读了,但不知道哪个适合这种需要。助手?命名范围?
I first tried a @books in the controller, but I need to know which book from the loop. I'm not sure the next step to learn about so I can remove the ugly. I've seen lots of things I want to go read up on, but not sure which suits this need. Helpers? Named scopes?
推荐答案
复杂这里是由事实介绍了使用 writer_id
等,而不是实际的关联的一部分,这可能会使事情变得更容易一些。如果你要与当前的结构,坚持,虽然,你有什么大概是pretty接近你想要什么,虽然你可能要更改的link_to
行以更简单:
Part of the complexity here is introduced by the fact by using writer_id
etc. instead of an actual association, which would probably make things a little bit easier. If you're going to stick with your current structure though, what you have is probably pretty close to what you want, although you may want to change that link_to
line to the more simple:
link_to book.creators.find(book.writer_id).name, creator_path(book.writer_id)
另一种选择是设置自定义的getter方法为模型中的作家和插画家,这将让你简化事情就更:
Another option would be to setup custom getter method for writer and illustrator in your model, which would let you simplify things even more:
# book.rb
def writer
creators.find(writer_id) # This should allow you to still eager load it if you want
end
def illustrator
creators.find(illustrator_id)
end
# in your view
link_to book.writer.name, creator_path(book.writer_id)
(你也可以写setter方法,虽然这会比较复杂一点,可能不值得的,除非你打算改变的创造者。)
(You could also write setter methods, although this would be a little bit more complex, and possibly not worth it unless you're planning on changing the creators.)
这篇关于从循环重构协会拿出来看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!