I have a one-to-many association in Ruby on Rails:
class Booking < ActiveRecord::Base
has_many :rides
accepts_nested_attributes_for :rides, allow_destroy: true
end
### and ###
class Ride < ActiveRecord::Base
belongs_to :bookings
end
The booking and ride views and controllers were scaffolded.
I wanted an "Add rides" button in my bookings form:
= simple_form_for(@booking) do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs
.container
.row
.col-6
= f.input :first_name
= f.input :phone_number
.col-6
= f.input :last_name
= f.input :email
.col-12
= f.input :company
### here is the simple fields that does not work:
= f.simple_fields_for :rides do |ride|
= render 'rides/form', :f => ride
= link_to_add_association 'add ride', f, :rides
However, nothing gets displayed and I don't know why.
Things I've tried:
- Add
rides_build
I tried to add this to the booking controller
def new
@booking = Booking.new
@booking.build_rides
end
But it only gave me an error "undefined method `build_rides' for #Booking:0x000000010575c578"
- Add
rides.build
def new
@booking = Booking.new
@booking.rides.build
end
This also gave me an error message: "undefined method `model_name' for nil:NilClass"
- Add only
ride
def new
@booking = Booking.new
@booking.build
end
This just didn't do anything. No error, but the problem wasn't solved.
- Change
ApplicationRecord
toActiveRecord::Base
This solved it for someone else, but not for me.
Might also want to add that absolutely nothing gets rendered that's inside the simple_fields_for, not even a simple h1
.
CodePudding user response:
Option 2 is the correct way and should work, but you have an error in your Ride
model, it should say
belongs_to :booking
Note: the simple_fields_for
iterates over nested children, as long as there are none, nothing will get rendered.