Search code examples
ruby-on-railsrubyruby-on-rails-2

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>

Solution

  • 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>