I have two models which are linked in a has_one / belongs_to association; Computer and Ipv6Address respectively.
I have pre-populated the Ipv6 table with all the entries that I want it to have, and I now need to have a drop-down list on the Computer new/edit forms to select an item from Ipv6 to associate it with.
Everything I’ve seen so far on this only seems to work when you are creating both objects at the same time on the new form and then subsequently editing them.
I’ve tried to set up my MVC’s as per the examples I’ve found online, but I keep getting errors, as underneath these code excerpts:
Computer model:
class Computer < ActiveRecord::Base
accepts_nested_attributes_for :ipv6_address
has_one :ipv6_address
...
Ipv6Address model:
class Ipv6Address < ActiveRecord::Base
attr_accessible :computer_id, :ip_address
belongs_to :computer
...
Computer controller:
class ComputersController < ApplicationController
def new
@computer = Computer.new
@ipv6s = Ipv6Address.where('computer_id IS NULL').limit(5)
end
def edit
@computer = Computer.find(params[:id])
@ipv6s = Ipv6Address.where('computer_id = #{@computer.id} OR computer_id IS NULL').order('computer_id DESC').limit(5)
end
Computer new form:
<%= simple_form_for( @computer ) do |f| %>
<%= f.fields_for :ipv6_addresses do |v6| %>
<%= v6.input :ipv6_address, :collection => @ipv6s %>
<% end %>
<% f.button :submit %>
<% end %>
Error when browsing to computer new form:
NoMethodError in ComputersController#new
private method `key?' called for nil:NilClass
No line of code reference is given for this error, but it only appears when I have the nested form included in the computer new form.
Any ideas as to what is causing it or how I can better go about what I’m doing?
EDIT:
As it turns out, I needed to have accepts_nested_attributes_for :ipv6_address after the line has_one :ipv6_address in the Computer model.
That fixed the issue with the form loading.
As per Yarden’s answer, I then also singularized all instances of “ipv6_address” so as to reflect the has_one relationship.
Once doing that in the new form, however, the ipv6 field completely disappeared. I’ll open a new question with this one if I can’t get it sorted out shortly.
Try adding ‘:’, I think that may be the problem :
Also you forgot to add a ‘.’ here:
Edit after change:
The problem is that its only a has_one relationship so it doesnt know the plural of :ipv6_address as you stated in your model… you need to change it to :ipv6_address instead of :ipv6_addresses…
Also in your form change the :ipv6_address to the actual field which is :ip_address.
So overall your form should look like this: