Search code examples
ruby-on-railsruby-on-rails-5simple-form

Unable to render (double) nested form


I have 3 models, Classses, ClassPrices & Bookings. ClassPrices belongs to Classses & Bookings belong to ClassPrices. I'm having trouble rendering the form for Bookings on the ClassPrices' page.

1. routes.rb

resources :classses do
  resources :class_prices do
    resources :bookings
  end
end

2. class_price.rb

class ClassPrice < ApplicationRecord
  belongs_to :classs
  has_many :bookings
end

3. bookings.rb

class Booking < ApplicationRecord
  belongs_to :user
  belongs_to :class_price
end

4. bookings_controller.rb

def new
  @booking = Booking.new
end    

I'm using the Simple Form gem, and due to the restriction in amount of code I can have, this is the header of my form:

<%= simple_form_for [@classs.class_prices, @class_price.bookings.new] do |f| %>

The error I'm getting is:

undefined method `to_model' for #<ClassPrice::ActiveRecord_Associations_CollectionProxy:0x00007fcf01a70ff8>
Did you mean?  to_xml

Edit:

5. class_prices_controller.rb

def show
  @classs = Classs.find(params[:classs_id])
  @class_price = ClassPrice.find(params[:id])
  @booking = Booking.new
  @classs.class_prices.find(params[:id]).bookings.create(booking_params)
end

Solution

  • undefined method `to_model' for ClassPrice::ActiveRecord_Associations_CollectionProxy:0x00007fcf01a70ff8

    @classs.class_prices returns a collection and the first argument in the simple_form_for(or any other form helpers) should never be a collection. I believe it should be

    <%= simple_form_for [@class_price, @class_price.bookings.new] do |f| %>
    

    Update:

    As per your routes, it should be

    <%= simple_form_for [@classs, @class_price, @booking] do |f| %>