Search code examples
ruby-on-railsrubyparentparent-childhas-and-belongs-to-many

Ruby on Rails - creating a child table in a habtm relationship


I have a list of tables that can be created fine. I want to then be able to create a child table by clicking Edit on the parent (goes to edit.html.erb) and then clicking 'New child'. The relationship between the parent and child tables is has_and_belongs_to_many.

<%= button_to 'New Child', new_parent_child_path([@parent, @parent.children.build]), :method => :get %>

This is the link to the new child form, producing the following error:

'undefined method `children' for nil:NilClass'

The server log gives me the following:

Started GET "/parents/1//children/new" for blah at blah
Processing by ChildrenController#new as HTML
  Parameters: {"parent_id"=>"1"}
  Rendered children/_form.html.erb (1.3ms)
  Rendered children/new.html.erb within layouts/application (1.9ms)
Completed 500 Internal Server Error in 4ms

ActionView::Template::Error (undefined method `children' for nil:NilClass):
    1: <%= form_for ([@parent, @parent.children.build]) do |f| %>
    2: 
    3: <div class = "field">
    4:   <%= f.label :Child_name %><br/>
  app/views/children      /_form.html.erb:1:in`_app_views_children__form_html_erb__2140243687_70034946643120'
  app/views/children/new.html.erb:3:in `_app_views_children_new_html_erb__655166082_70034947829100'

The _form.html.erb that renders in the child new.html.erb is as follows:

<%= form_for ([@parent, @parent.children.build]) do |f| %>

<div class = "field">
  <%= f.label :Child_name %><br/>
  <%= f.text_field :ChildName %>
</div>

<div class = "field">
  <%= f.label :Child_email_address %><br/>
  <%= f.text_field :ChildEmail %>
</div>

<div class = "actions">
  <%= f.submit %>
</div>
<% end %>

(Note: the tables are not actually called parent and child, I just used those names for secrecy's sake. Also, please don't advise me to use has_many through, I'm not interested.)

Edit #1: Code from 'ChildrenController'

  def new
    @child = Child.new
  end

  def create
    @parent = Parent.find(params [:parent_id])
    @scout = @parent.children.build(params[:child])
    redirect_to parent_path(@parent)
  end

Solution

  • You need to include @parent = Parent.find(params[:parent_id]) in the new action because you are using it in the new.html.erb template. Otherwise it will be nil and @parent.children.build will not work.