'page'可能有'多个'部分'。所以我想为页面包含的每个“部分”检索'sections.title'。我不明白为什么我的阻止Do
不起作用,但这有效sections.each { |n| p n.id }
2.0.0-p353 :041 > pages = Page.find(52).sections.count
Page Load (0.3ms) SELECT `pages`.* FROM `pages` WHERE `pages`.`id` = 52 LIMIT 1
(0.3ms) SELECT COUNT(*) FROM `sections` WHERE `sections`.`page_id` = 52
=> 2
2.0.0-p353 :042 > pages =Page.find(52).sections
Page Load (0.3ms) SELECT `pages`.* FROM `pages` WHERE `pages`.`id` = 52 LIMIT 1
Section Load (0.2ms) SELECT `sections`.* FROM `sections` WHERE `sections`.`page_id` = 52
=> #<ActiveRecord::Associations::CollectionProxy [#<Section id: 20, title: "La victoire est proche", body: "Guinsly t'e le meilleur Oat cake sweet roll browni...", page_id: 52, created_at: "2014-01-22 01:40:14", updated_at: "2014-01-22 01:40:14">, #<Section id: 36, title: "La victoire est proche", body: "Guinsly t'e le meilleur Oat cake sweet roll browni...", page_id: 52, created_at: "2014-01-22 01:40:15", updated_at: "2014-01-22 01:40:15">]>
2.0.0-p353 :044 > pages.each do |n|
2.0.0-p353 :045 > p.title
2.0.0-p353 :046?> end
NoMethodError: undefined method `title' for nil:NilClass
or
...
2.0.0-p353 :055 > Page.find(52).sections.each { |n| p n.id }
Page Load (0.3ms) SELECT `pages`.* FROM `pages` WHERE `pages`.`id` = 52 LIMIT 1
Section Load (0.3ms) SELECT `sections`.* FROM `sections` WHERE `sections`.`page_id` = 52
20
36
答案 0 :(得分:1)
您的每个区块都在寻找您使用n
而不是p
...
pages.each do |n|
n.title
end
虽然p
更有意义,但您可以在这两个地方使用p
代替n
。
或者您是否尝试使用p
方法打印值?然后:
pages.each do |page|
p page.title
end