0

在我看来,我发送一个 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"]:Array268并且test-1是第一行结果的idand 。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问题的数量很难找到答案。

4

1 回答 1

2

您遇到此问题是因为您没有使用 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,则不要使用idand 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')
于 2013-08-23T11:43:21.633 回答