2016-07-28 118 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