我用蒂博的教程想我的手在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:類型這使得'類型'零。所以我刪除了,現在它正在
它不是一個語法錯誤,你的'type'是'nil'地方。 –