Reputation: 5527
I have a pretty basic association:
# user.rb
class User < ActiveRecord::Base
has_many :services, :through => :subscriptions
has_many :subscriptions, :accessible => true
accepts_nested_attributes_for :subscriptions
end
# service.rb
class Service < ActiveRecord::Base
has_many :users, :through => :subscriptions
has_many :subscriptions
end
# subscription.rb
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :service
end
The Subscription has also a boolean column "notification" which I need to configure individually, so i looked into the API, followed the example and came up with this code for my form:
- if current_user.subscriptions.length > 0
%fieldset#subscriptions
%legend Abonnements
%table
%tr
%th.name
%th.notification Notifications?
- for subscription in current_user.subscriptions do
%tr
- f.fields_for :subscriptions, subscription do |s|
%td=subscription.service.name
%td= s.check_box :notification
But when I save the Form, all associated subscriptions are destroyed. Whereas when I check the checkbox it wont be deleted, but the checkbox is not saved either. Does anyone know what I'm doing wrong?
Upvotes: 2
Views: 1760
Reputation: 5527
After trying around for almost 2 hours, i finally got it working. A slight change to your code would've been enough:
# _form.html.haml
# […]
- if current_user.subscriptions.length > 0
%fieldset#subscriptions
%legend Abonnements
%table
%tr
%th.name
%th.notification Notifications?
- f.fields_for :subscriptions do |sub|
%tr
%td= sub.object.service.name
%td
= sub.check_box :notification
= hidden_field_tag "user[service_ids][]", sub.object.service.id
# […]
Because params[:user][:service_ids]
was empty, it deleted the whole association.
Upvotes: 2
Reputation: 7880
You're not submitting any subscriptions with the form. Without clicking the checkbox, you've got nothing to submit for that subscription, so the subscriptions are being wiped out by the nested attributes functionality. Try putting in a hidden field with the subscription's service id.
I believe you also are setting up the form for nested attributes incorrectly. Try this:
- if current_user.subscriptions.length > 0
%fieldset#subscriptions
%legend Abonnements
%table
%tr
%th.name
%th.notification Notifications?
- f.fields_for :subscriptions do |sub|
%tr
%td= sub.object.service.name
%td
= sub.check_box :notification
= sub.hidden_field :service_id
Upvotes: 0