2016-07-28 47 views
0

我用蒂博的教程想我的手在STI:https://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-3未定義的方法「下劃線」

它一直在努力罰款直至動態路徑部分在那裏我得到「未定義的方法`下劃線」的零:對NilClass'這個片段

def format_sti(action, type, post) 
    action || post ? "#{format_action(action)}#{type.underscore}" : "#{type.underscore.pluralize}" 
end 

路線:

resources :blogs, controller: 'posts', type: 'Blog' do 
      resources :comments, except: [:index, :show] 
    end 
    resources :videos, controller: 'posts', type: 'Video' 
    resources :posts 

柱控制器:

before_action :set_post, only: [:show, :edit, :update, :destroy] 
    before_action :set_type 
    def index 
     @posts = type_class.all 
    end 
    ... 
    private 

    def set_type 
     @type = type 
    end 

    def type 
     Post.types.include?(params[:type]) ? params[:type] : "Post" 
    end 

    def type_class 
     type.constantize 
    end 

    def set_post 
     @post = type_class.find(params[:id]) 
    end 

帖子助手:

def sti_post_path(type = "post", post = nil, action = nil) 
     send "#{format_sti(action, type, post)}_path", post 
    end 

    def format_sti(action, type, post) 
     action || post ? "#{format_action(action)}#{type.underscore}" : "#{type.underscore.pluralize}" 
    end 

    def format_action(action) 
     action ? "#{action}_" : "" 
    end 

後的index.html

<% @posts.each do |p| %> 

    <h2><%= p.title %></h2> 
    Created at: <%= p.created_at %><BR> 
    Created by: <%= p.user.name %><P> 
    <%= link_to 'Details', sti_post_path(p.type, p) %><P> 
    <% end %> 

,當我嘗試訪問的index.html出現錯誤,我沒有嘗試過其他的聯繫呢。我嘗試刪除'下劃線',然後'_path'成爲一個未定義的方法。我也嘗試過其他的建議,如「GSUB」,但它也表明它作爲一個未定義的方法,這使我認爲這是一個語法錯誤...

UPDATE: 我有attr_accessor:類型這使得'類型'零。所以我刪除了,現在它正在

+0

它不是一個語法錯誤,你的'type'是'nil'地方。 –

回答

0

在你PostsHelper.rb

def format_sti(action, type, post) 
    action || post ? "#{format_action(action)}#{type.underscore}" : "#{type.underscore.pluralize}" 
end 

該方法的其他部分有 .underscore。 類型可能沒有在這裏。爲了驗證它,試試這個:

def format_sti(action, type, post) 
    action || post ? "#{format_action(action)}#{type.underscore}" : "#{"post".underscore.pluralize}" 
end 
+0

謝謝!我不得不用'post'替換'type'來使其工作。爲什麼會這樣? – user1636937

+0

我有一個想法的含義。當我到我的Rails控制檯並調用post.type時,即使描述中顯示它是「博客」或「視頻」,它也會返回零。 – user1636937

0

嘗試try命令,該命令將不會返回NoMethodError exception,並返回零代替,

def format_sti(action, type, post) 
    action || post ? "#{format_action(action)}#{type.try(:underscore)}" : "#{type.try(:underscore).pluralize}" 
end 

定義: 使用try,一個NoMethodError異常不會如果接收對象是一個零對象或NilClass,則將被提升並返回nil。

Here is the reference

+0

我試過了,它返回了一個不同的錯誤,這種類型從這一行識別'_path'爲未知方法: send「#{format_sti(action,type,post)} _ path」,post – user1636937