在我的 Controller 中,我尝试运行一个查询来获取另一个表中未引用的所有 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
逻辑接口(interface).rb
# no relationship defined
更新
这就是表单的生成方式:
<%= form_tag :controller => "circuit", :action => "update" %>
# other inputs
<%= select_tag options_for_select(@vlan_numbers) %>
# other inputs
</form>
最佳答案
您可以将 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>
关于ruby-on-rails - Rails 未定义数组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18226909/