Why can’t ActiveRecord_Relation call instance methods? How should this be achieved?

  question, ruby

The data design is like this:

section belongs_to :page
page has_many :sections

Want to realize the function is:

Use public#show to display all sections contained in the Page of the corresponding permalink.
get ‘show/:permalink’, :to => ‘public#show’

Controller code

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 is found through the where condition

`irb(main):048:0> p4 = Page.where(permalink:”page4″)
Page Load (0.4ms) SELECTpages.* FROMpagesWHEREpages.permalink= ‘page4’
=> #<ActiveRecord::Relation [#<Page id: 43, subject_id: 28, name: “page4”, permalink: “page4”, position: 1, visible: true, created_at: “2016-05-27 06:43:27”, updated_at: “2016-05-27 06:43:54”>]>`

P5 found the data directly. I think p4 and p5 are the same, and both can call Page’s instance method.

`irb(main):057:0> p5 = Page.last
Page Load (0.4ms) SELECTpages.* FROMpagesORDER BYpages.idDESC LIMIT 1
=> #<Page id: 43, subject_id: 28, name: “page4”, permalink: “page4”, position: 1, visible: true, created_at: “2016-05-27 06:43:27”, updated_at: “2016-05-27 06:43:54”>`

But the result is not:

`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)`

The error was reported as follows

`
undefined method `sections’ for #<Page::ActiveRecord_Relation:0x007facb084bc50>
Extracted source (around line #5):

<h2><%= @page.name %></h2>

<% @page.sections.visible.sorted.each do |section| %>
<div class=”section”>

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

`

This problem has been solved, thank you!

加一个.first
@page = Page.where(:permalink => params[:permalink], :visible => true).first