Search code examples
ruby-on-railsnamespacesmany-to-manyform-for

form_for with a namespaced resource with a many to many relationship


I'm getting stuck getting a form_for to work with a namespaced resource that has a many to many relationship I need to reference in the form.

The relationship is stretches impact many body areas and body areas can have many stretches.

Here's the resource:

namespace :admin do
  resources :stretches, only: [:new, :create, :edit, :update, :destroy]
  resources :body_areas, only: [:new, :create]
end

Here's the form_for:

<%= form_for [:admin, @stretch, @body_area] do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :body_area_id %>
  <%= f.collection_select :body_area_id, BodyArea.all, :id, :name, prompt: 'Select a Body Area' %>

  <%= f.submit %>
<% end %>

And my controller:

  def new
    @stretch = Stretch.new
    @body_area = BodyArea.all
  end

The error I'm getting is:

ActionView::Template::Error:
   undefined method `to_key' for #<ActiveRecord::Relation [#<BodyArea id: 1, name: "Legs 1">]>

Does anyone have any suggestions that could help me out? Thanks in advance for your time!


Solution

  • ActionView::Template::Error: undefined method `to_key' for ActiveRecord::Relation BodyArea id: 1, name: "Legs 1"

    I believe the error is due to because of @body_area = BodyArea.all. It should be @body_area = BodyArea.new

    def new
      @stretch = Stretch.new
      @body_area = BodyArea.new
    end
    

    However, as per your routes, your form is wrong. It seems like you are creating a new Stretch. If so, your form should look like this

    <%= form_for [:admin, @stretch] do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>
    
      <%= f.label :body_area_id %>
      <%= f.collection_select :body_area_id, BodyArea.all, :id, :name, prompt: 'Select a Body Area' %>
    
      <%= f.submit %>
    <% end %>