سؤال

لدي جمعية أساسية جميلة:

# 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

يحتوي الاشتراك أيضا على "إخطار" عمود منطقي "الذي أحتاجه لتكوينه بشكل فردي، لذلك نظرت إلى api., اتبع المثال وتوصل إلى هذا الرمز الخاص بنموذجي:

- 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

ولكن عندما أحفظ النموذج، يتم تدمير جميع الاشتراكات المرتبطة. بينما عندما أتحقق من خانة الاختيار، لن يتم حذفها، ولكن لا يتم حفظ مربع الاختيار إما. وبعد هل يعرف أحد ما أفعله خطأ؟

هل كانت مفيدة؟

المحلول

بعد المحاولة حوالي ساعتين تقريبا، حصلت أخيرا على ذلك. تغيير طفيف في الكود الخاص بك سيكون كافيا:

# _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
# […]

لأن params[:user][:service_ids] كان فارغا، وحذف الجمعية بأكملها.

نصائح أخرى

أنت لا تقدم أي اشتراكات مع النموذج. بدون النقر فوق خانة الاختيار، فلن تحصل على أي شيء لتقديمه لهذا الاشتراك، وبالتالي يتم القضاء على الاشتراكات من خلال وظائف السمات المتداخلة. حاول وضع حقل مخفي مع معرف خدمة الاشتراك.

أعتقد أنك أيضا إنشاء نموذج للسمات المتداخلة بشكل غير صحيح. جرب هذا:

- 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top