Rails未定义的数组方法

时间:2013-08-14 08:39:40

标签: ruby-on-rails ruby ruby-on-rails-2

在我的控制器中,我试图运行一个查询来获取所有未在另一个表中引用的id,如下所示:

@vlan_numbers = ActiveRecord::Base.connection.execute("SELECT pop_vlans.id, vlan_number FROM pop_vlans WHERE pop_vlans.id NOT IN (SELECT logical_interfaces.vlan_id FROM logical_interfaces) AND pop_id != " + @pop_id.to_s)

然后在我看来,我试图使用collection_select在下拉菜单中显示这些内容:

但我得到的错误是undefined method 'vlan_number' for [2, "2"]:Array,其中这些值只是查询结果的第一行。

这是涉及的两个表的图表:

logical_interfaces | pop_vlans
-------------------|-----------
     vlan_id-------|----->id
       ....        |  vlan_number

并且模型中的关系是:

pop_vlan.rb

belongs_to :logical_interface

logical_interface.rb

# no relationship defined

更新

这是表单的生成方式:

<%= form_tag :controller => "circuit", :action => "update" %>
    # other inputs
    <%= select_tag options_for_select(@vlan_numbers) %>
    # other inputs
 </form>

2 个答案:

答案 0 :(得分:4)

您可以select使用options_for_select(@vlan_numbers)代替collection_select

来自ActiveRecord::Base.connection.execute

结果未加载到模型中

相反,你可以试试YourModelName.find_by_sql(...)如果你想玩你的模特

<强>更新 假设您希望此select_tag填充的属性名称为vlan_id,那么:

<%= form_tag :controller => "circuit", :action => "update" %>
  # other inputs
  <%= select_tag 'vlan_id', options_for_select(@vlan_numbers) %>
  # other inputs
</form>

答案 1 :(得分:1)

ActiveRecord::Base.connection.execute返回Mysql2::Result而不是Arel / AR查询的对象数组。

因此它返回包含pop_vlans.id, vlan_number的数组数组。因此,必须在collection_select中使用first或last,而不是something.vlan_number

因此您必须使用options_for_select代替collection_select,例如:

options_for_select(@vlan_numbers.collect{|v| v.first})