rails:association:nil的未定义方法`title':NilClass

时间:2014-01-24 05:50:41

标签: ruby-on-rails ruby-on-rails-4

'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

1 个答案:

答案 0 :(得分:1)

您的每个区块都在寻找您使用n而不是p ...

pages.each do |n|
  n.title
end

虽然p更有意义,但您可以在这两个地方使用p代替n

或者您是否尝试使用p方法打印值?然后:

pages.each do |page|
  p page.title
end