I’m building a recurring billing system and am having trouble with a nested form. The following code works, but makes a POST with:
"customer"=>{"service"=>{"service_id"=>"1"}}
It should be Customer.services instead of Customer.service. However, if I change the form to reference fields_for :services, it doesn’t render a dropdown at all.
_form.html.haml
= form_for @customer do |f|
= f.fields_for :service do |service_fields|
= service_fields.collection_select(:service_id, Service.all, :id, :name, { :prompt => 'Select Package' })
= f.submit "Add Service", class: "btn"
models/customer.rb
class Customer < ActiveRecord::Base
has_many :subscriptions, :dependent => :destroy
has_many :services, :through => :subscriptions
accepts_nested_attributes_for :services
end
models/service.rb
class Service < ActiveRecord::Base
has_many :customers, :through => :subscriptions
has_many :subscriptions
end
models/subscription.rb
class Subscription < ActiveRecord::Base
belongs_to :customer
belongs_to :service
end
So, in this situation you want to build a
subscriptionon thecustomer. Since you’re pretty much on the right track, it should be as simple as changing this_form.html.haml
models/customer.rb
Right now the reason why you’re getting anything rendered is because you’re causing the form to submit with a new “attribute” called
servicewith then returns the data from thefields_for. Withaccepts_nested_attributes_for {model}you should be looking for aparamswith something like{model}_attributesAlso the reason why you’re not getting anything rendered when you use
:servicesin thefields_foris becauseServicedoesn’t respond toservice_id.