繁体   English   中英

Rails未定义的方法“ sections”进行关联

[英]Rails undefined method `sections' for association

Page has_many Section,这样一个Section includes_to Pages。 因此,如果我想检索页面的所有“部分”,则应该像“ Page.sections”那样编写它,但是我遇到了错误。

2.0.0-p353 :042 > pages = Page.where(id: 48)
Page Load (0.4ms) SELECT `pages`.* FROM `pages` WHERE `pages`.`id` = 48
=> #<ActiveRecord::Relation [#<Page id: 48, name: "---\n- français\n", parent_id: 36, created_at: "2014-01-22 00:33:48", updated_at: "2014-01-22 00:33:48">]>
2.0.0-p353 :043 > section = Section.where(page_id: 48).count
(0.3ms) SELECT COUNT(*) FROM `sections` WHERE `sections`.`page_id` = 48
=> 3
2.0.0-p353 :044 > pages.sections
NoMethodError: undefined method `sections' for #<ActiveRecord::Relation::ActiveRecord_Relation_Page:0x00000004f53c60>
...
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

您当前有一组页面。 使用时

Page.where(id: 48)

您将得到一个数组返回给您。 你想做的是

Page.find 48

这将仅返回一个元素。 在这种情况下,您应该可以毫无问题地使用sections方法。

如果由于某种原因要使用.where ,可以使用类似

pages.first.sections

来检索列表中FIRST元素的各个部分(当将whereid一起使用时,应仅在数组中获得一个元素)

暂无
暂无

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

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