ruby - 为什么ActiveRecord_Relation不能调用实例方法?该怎么实现?

 手机用户2502874905 发布于 2022-10-26 23:15

数据设计大概是这样的:

section belongs_to :page
page has_many :sections

想实现的功能是:

利用public#show来显示相应permalink的Page所包含的所有sections.
get 'show/:permalink', :to => 'public#show'

controller 代码

class PublicController < ApplicationController

  layout 'public'

  def index
    # intro text
    
  end

  def show
    @page = Page.where(:permalink => params[:permalink], :visible => true)
    puts "get permalink:", params[:permalink]
    puts "permalink",@page
    if @page.nil?
      redirect_to(action: 'index')
    else
      #display the page content using show .html.erb
      
    end
  end
end

p4是通过where条件查出来的

`irb(main):048:0> p4 = Page.where(permalink:"page4")
Page Load (0.4ms) SELECT pages.* FROM pages WHERE pages.permalink = 'page4'
=> #]>`

p5是直接找到了那条数据,我认为p4和p5是一样的,都可以调用Page的实例方法

`irb(main):057:0> p5 = Page.last
Page Load (0.4ms) SELECT pages.* FROM pages ORDER BY pages.id DESC LIMIT 1
=> #`

可结果确不行:

`irb(main):065:0* p4.class
=> Page::ActiveRecord_Relation
irb(main):066:0> p5.class
=> Page(id: integer, subject_id: integer, name: string, permalink: string, position: integer, visible: boolean, created_at: datetime, updated_at: datetime)`

报错如下

`
undefined method `sections' for #
Extracted source (around line #5):

<%= @page.name %>

<% @page.sections.visible.sorted.each do |section| %>

<% case section.content_type %>
<% when 'HTML' %>

`

2 个回答
  • 你 migration 的代码能看下么?

    2022-10-27 01:34 回答
  • 此问题已解决,谢谢大家!

    加一个.first
    @page = Page.where(:permalink => params[:permalink], :visible => true).first
    2022-10-27 01:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有