【发布时间】:2014-12-15 13:21:28
【问题描述】:
我刚刚实现了基于 Ryan Bates 的 rails cast #340 'http://railscasts.com/episodes/340-datatables?autoplay=true' 的数据表,我收到了这个错误 'undefined method `map' for nil:NilClass'。我所看到的所有地方,人们都在说这是因为你试图调用的内容是未定义的,但在这种情况下,我不确定为什么这是一个错误,因为它正在被定义,我已经按照这个 rails cast 到最后一个细节。
我得到的错误是“undefined method `map' for nil:NilClass” 堆栈跟踪如下:
Showing /Users/calligouser/Documents/CalligoProjects/cloudcentrev2/app/views/ips/index.html.erb where line #7 raised:
<li class="left"><%= select_tag 'ip_status_id', options_for_select(@ip_statuses, @status_id), { prompt: "All" } %></li>
在定义@ip_statuses 时,控制器中会出现此错误.map。代码进入模型,在该模型中检索值的哈希值,如下所示:
STATUSES = { 0 => "Unallocated",
1 => "Allocated",
2 => "Reserved",
3 => "Transient"
}
我正在尝试在 IP 索引视图中加载 IP 地址数据表。
IP 控制器(索引)
def index
@ips = Ip.all
respond_to do |format|
format.html
format.json { render json: IpsDatatable.new(view_context) }
end
@ip_statuses = Ip::STATUSES.map {|key,value| [value,key]}
end
用于数据表选项的 ips_datatable.rb 文件
class IpsDatatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view
def initialise(view)
@view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i
iTotalRecords: Ip.count,
iTotalDisplayRecords: ips.total_entries,
aaData: data
}
end
private
def data
ips.map do |ip|
[
link_to(ip.ip_address, ip),
h(ip.system_name),
h(ip.description),
h(ip.system_location),
h(ip.status)
]
end
end
def ips
@ips ||= fetch_ips
end
def fetch_ips
ips = Ip.order("#{sort_column} #{sort_direction}")
ips = ips.page(page).per_page(per_page)
if params[:sSearch].present?
ips = ips.where("name like :search or category like :search", search: "%#{params[:sSearch]}")
end
ips
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns = %w[ip_address system_name system_location description status]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir0] == "desc" ? "desc" : "asc"
end
end
IPs JQuery 文件
jQuery ->
# -------------------------------------------------------------------------
# DataTables Server Side
# -------------------------------------------------------------------------
$('#ip-table').dataTable
sPaginationType: "full_numbers"
bJQueryUI: true
bProcessing: true
bServerSide: true
sAjaxSource: $('#ip-table').data('source')
IP 表表单视图
<table id="ip-table" class="full display" data-source="<%= products_url(format: "json") %>">
<thead>
<tr>
<th>Ip address</th>
<th>System name</th>
<th>Description</th>
<th>System location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
编辑:我发现应用程序没有超出 respond_to 块,所以我尝试在 ip_datatables 文件中进行调试,并且在到达文件中的代码之前应用程序似乎失败了.我在 format.json 代码行之后使用了 puts '....',它确实达到了这一点,但由于某种原因,它没有从 ip_datatables 文件中返回。
【问题讨论】:
标签: jquery ruby-on-rails datatable server-side