My "has_many through" join model has a null reference after saving

I am trying to create an object and add an existing object to the has_many through association, but after saving my object, the link to my newly created object is set to nil in the connection model.

To be specific, I create a Notification object and add a preexisting Member object to the Notification.members association. I use nested resources and I call the new notification controller function using the following relative URL: / Members / 1 / notification / new

After filling out the form and submitting the function, create is also called from what I understand from the Rails Association manual , section 4.3. 3 “When are the objects saved?”, A Member Association must be created in the database when saving a new notification object:

"If the parent (the one who declares the has_many association) is unsaved (that is, new_record? Returns true), then the children are not saved when they are added. All unsaved members of the association will be automatically saved if the parent is saved."

After creating the notification object, the following record was created in the database:

select id, notification_id, notifiable_type, notifiable_id from deliveries; 
1|<NULL>|Member|1 

, - . , , . , , .

? .: D

class Notification < ActiveRecord::Base
  has_many :deliveries, :as => :notifiable
  has_many :members, :through => :deliveries, :source => :notifiable, :source_type => "Member"
  has_many :groups, :through => :deliveries, :source => :notifiable, :source_type => "Group"
end

class Member < ActiveRecord::Base
  has_many :deliveries, :as => :notifiable
  has_many :notifications, :through => :deliveries
end

class Delivery < ActiveRecord::Base
  belongs_to :notification
  belongs_to :notifiable, :polymorphic => true
end

# Group is not really relevant in this example.
class Group < ActiveRecord::Base 
  has_many :deliveries, :as => :notifiable
  has_many :notifications, :through => :deliveries
end

Controller

class NotificationsController < ApplicationController
  def create
    @notification = Notification.new(params[:notification])
    @member = Member.find(params[:member_id])
    @notification.members << @member

    respond_to do |format|
      if @notification.save
        ...
      end
    end
  end
end
+3
1

Rails. , , .

, , :

def create
    @notification = Notification.new(params[:notification])
    @member = Member.find(params[:member_id])

    respond_to do |format|
      if @notification.save
        @member.notifications << @notification
        @member.save
        ...
+2

All Articles