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

逻辑接口.rb

# no relationship defined

更新

这是生成表单的方式:

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

2 回答 2

4

您可以使用selectwithoptions_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>
于 2013-08-14T08:53:19.767 回答
1

ActiveRecord::Base.connection.execute不像 Arel/AR 查询那样返回Mysql2::Result对象数组。

所以它返回包含 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}) 
于 2013-08-14T08:50:50.313 回答