在我的控制器中,我试图运行一个查询来获取所有未在另一个表中引用的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>
答案 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})