我试图创建一个对象,并添加一个现有的对象到“has_many通过”关联,但保存我的对象后,我的新创建的对象的引用设置在连接模型中为零。我的“has_many通过”加入模型保存后没有引用
具体而言,我创建了一个Notification对象,并将一个预先存在的Member对象添加到Notification.members关联中。我使用嵌套的资源,我用以下相对URL调用通知控制器的新功能: /会员/ 1 /通知/新
填写表单并提交后,创建函数被调用,从我从Rails Associations guide了解,第4.3.3节“?当对象保存”,各成员协会应在数据库中创建时,新通知对象保存:
“如果父对象(一个声明has_many关联)未保存(即new_record?返回true),那么子对象在添加时不会被保存。关联的所有未保存的成员将自动当父母被保存时被保存。“
创建通知对象后,以下记录在数据库中创建:
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
控制器
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