模型患者belongs_to
FeedList,has_many
患者。我正在尝试,在创建新的FeedList时,我想将当前在DB中的所有患者添加到FeedList中。我目前正试图在create
feed_lists_controller.rb
内进行此操作。
def create
@feed_list = FeedList.new(feed_list_params)
Patients.all.each do |p|
@feed_list.patients << p
end
respond_to do |format|
if @feed_list.save
format.html { redirect_to @feed_list, notice: 'Feed list was successfully created.' }
format.json { render :show, status: :created, location: @feed_list }
else
format.html { render :new }
format.json { render json: @feed_list.errors, status: :unprocessable_entity }
end
end
end
但是,当我创建新的FeedList
时,它似乎没有注册[8] pry(main)> FeedList.create
=> #<FeedList:0xbaf7bdd0
id: 3,
created_at: Sun, 29 Nov 2015 01:11:54 UTC +00:00,
updated_at: Sun, 29 Nov 2015 01:11:54 UTC +00:00,
date: nil,
integer: nil>
[9] pry(main)> FeedList.last.patients
=> #<Patient::ActiveRecord_Associations_CollectionProxy:0x-2284f570>
FeedList.rb:
class FeedList < ActiveRecord::Base
has_many :patients
after_create :add_patients
private
def add_patients
::Patients.all.each do |p|
self.patients << p
end
end
end
我是在正确的轨道上吗?
答案 0 :(得分:2)
尝试在FeedList模型文件中使用callback:
after_create :add_patients
private
def add_patients
Patient.all.each do |p|
self.patients << p
end
end
正如Jason在上面提到的那样#34;创建动作[在您的控制器中]并不是每次创建模型实例时都会调用的回调&#34;。有关什么是回调的信息,请参阅What is a callback function?。 after_create
回调基本上是在您致电add_patients
后立即调用FeedList.create