Question

I have a User model that has many Subscriptions (categories of e-mail notifications). Whether a user receives e-mails corresponding to a given subscription depends on whether the active field in the subscription is true or false. I'm trying to use Simple Form's association method to allow users to subscribe or unsubscribe by changing the value of the active field:

= simple_form_for @user do |f|
  = f.input :name
  = f.input :email, label: "E-mail"
  = f.association :subscriptions, collection: @user.subscriptions,
    as: :check_boxes, value_method: :active, checked: lambda { |subscription| subscription.active? }

  = f.button :submit, "Save"

This does seem to correctly display the subscriptions with corresponding check boxes whose checked state corresponds to the value in the database. But checking or unchecking the boxes and submitting the form seems not to have any effect on the database.

Was it helpful?

Solution

I think you should use simple_fields_for here. That way it will be submitted as a nested form and be automatically saved in database. I'm not sure whether association can be used to save attributes of the associated model.

= simple_form_for @user do |f|
  = f.input :name
  = f.input :email, label: "E-mail"
  - f.simple_fields_for :publications do |subscription|
    # Here you have all simple_form methods available
    = subscription.check_box :active

  = f.button :submit, "Save"

Also note that you will have to add accepts_nested_attributes_for :subscriptions in the User model. And you will need to add this in your User model:

attr_accessible :subscriptions_attributes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top