在我看来,我发送了一个ajax请求以获取device_ports
特定的device
。
以前我用过
def get_device_ports
if params[:id] != ''
@device_ports = Device.find(params[:id]).device_ports.all(:order => 'id ASC')
output = '<option value="">Select Device Port...</option>'
@device_ports.each do |device_port|
output = output + '<option value="' + device_port.id.to_s + '">' + device_port.name + '</option>'
end
render :text => output
else
render :text => '0'
end
end
哪一个工作,但现在已经改变了我的查询我得到一个错误undefined method 'name' for [268, "test-1"]:Array
使用268
,并test-1
作为id
与name
结果的第一行。
这是我更新的代码:
def get_device_ports
if params[:id] != '' and params[:device_id] != ''
# @device_ports = Device.find(params[:id]).device_ports.all(:order => 'id ASC')
device_id = params[:device_id]
# Need a list of ports that aren't in use or are multiuse
@device_ports = ActiveRecord::Base.connection.execute('SELECT DISTINCT d.id, d.name FROM device_ports d LEFT OUTER JOIN circuits c ON c.physical_port_id = d.id WHERE (c.physical_port_id IS NULL AND d.device_id = ' + device_id + ') OR (d.multiuse = 1 AND d.device_id = ' + device_id + ') ORDER BY d.id ')
output = '<option value="">Select Device Port...</option>'
@device_ports.each do |device_port|
output = output + '<option value="' + device_port.id.to_s + '">' + device_port.name + '</option>'
end
render :text => output
else
render :text => '0'
end
end
我只是不确定为什么会收到错误,我想这是微不足道的,但是由于存在许多不同的NoMethodError
问题,因此很难找到答案。
之所以遇到这个问题,是因为您没有将ActiveRecord用作ORM来包装对象,而是执行了一个查询并处理了一系列的结果数组。我建议像这样更改您的查询:
@device_ports = Device.find(device_id).device_ports.includes(:circuits).
where('device_ports.multiuse = 1 OR circuits.id IS NULL').
order('device_ports.id').distinct
如果您绝对希望避免使用ActiveRecord,请不要使用id
和name
,而是将每条记录视为一个数组:
output << %Q{<option value="#{device_port.first}">#{device_port.last}</option>}
更新
我只是注意到您正在使用RoR-2。尽管比较痛苦,但是您仍然可以使用ActiveRecord查询,如下所示:
@device_ports = DevicePort.all(
:joins => "LEFT JOIN circuits c ON device_ports.id = c.devic_port_id",
:conditions => ['device_ports.device_id = ? AND (device_ports.multiuse = 1 OR c.id IS NULL)', device_id],
:order => 'device_ports.id',
:select => 'DISTINCT device_ports.id, device_ports.name')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句