ruby - 为什么ActiveRecord_Relation不能调用实例方法?该怎么实现?
淡淡烟草味
淡淡烟草味 2017-04-24 16:00:44
0
2
828

数据设计大概是这样的:

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'
=> #<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是直接找到了那条数据,我认为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
=> #<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">`

可结果确不行:

`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 #<Page::ActiveRecord_Relation:0x007facb084bc50>
Extracted source (around line #5):

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

<% @page.sections.visible.sorted.each do |section| %>
<p class="section">

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

`

淡淡烟草味
淡淡烟草味

모든 응답(2)
世界只因有你

이 문제는 해결되었습니다. 모두 감사합니다!

.first를 추가하세요
으아아아
左手右手慢动作

마이그레이션 코드를 볼 수 있나요?

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!