简体   繁体   中英

Rails undefined method for array

In my controller I am trying to run a query to get all of the id's not referenced in another table like so:

@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)

Then in my view I am trying to use collection_select to show these in a dropdown menu:

but the error I get is undefined method 'vlan_number' for [2, "2"]:Array where those values are just the first row of results from the query.

This is a diagram of the two tables involved:

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

and the relationships in the models are:

pop_vlan.rb

belongs_to :logical_interface

logical_interface.rb

# no relationship defined

Update

This is how the form is generated:

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

You can use select with options_for_select(@vlan_numbers) instead of collection_select

results from ActiveRecord::Base.connection.execute doesn't get loaded into a model

Instead you could try YourModelName.find_by_sql(...) If you want to play with your model

UPDATE Assuming the name of your attribute you want this select_tag to populate is vlan_id so:

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

ActiveRecord::Base.connection.execute returns Mysql2::Result not array of object as Arel/AR query does.

So it returns array of arrays containing pop_vlans.id, vlan_number . So have to use first or last in your collection_select instead of something.vlan_number

So you have to use options_for_select instead of collection_select like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM