首頁  >  問答  >  主體

ruby - 為什麼ActiveRecord_Relation不能呼叫實例方法?怎麼實現?

資料設計大概是這樣的:

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 . page4'=> #]>`
p5是直接找到了那條數據,我認為p4和p5是一樣的,都可以呼叫Page的實例方法

`irb(main):057:0> p5 = Page.last

Page Load (0.4ms) SELECT

pages
.* FROM pages ORDER BY pages.pages ORDER BY pages.
pages

ORDER BY

pages

.

。 Page id: 43, subject_id: 28, name: "page4", permalink: "page4", position: 1, visible: true, created_at: "2016-05-27 06:43:27", updated_at:52016-0 -27 06:43:54">`

可結果確不行:

`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' %>
🎜`🎜
淡淡烟草味淡淡烟草味2709 天前837

全部回覆(2)我來回復

  • 世界只因有你

    世界只因有你2017-04-24 16:02:44

    此問題已解決,謝謝大家!

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

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-24 16:02:44

    你 migration 的程式碼能看下麼?

    回覆
    0
  • 取消回覆