【发布时间】:2011-08-18 19:49:52
【问题描述】:
我正在尝试创建一个对象并将现有对象添加到“has_many through”关联,但是在保存我的对象后,对我新创建的对象的引用在连接模型中设置为 nil。
具体来说,我正在创建一个 Notification 对象并将一个预先存在的 Member 对象添加到 Notification.members 关联。我正在使用嵌套资源,并且正在使用以下相对 URL 调用通知控制器的新函数: /members/1/notifications/new
填写表单并提交后,调用create函数,据我了解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
【问题讨论】:
标签: ruby-on-rails polymorphic-associations has-many-through