2015-11-28 104 views
0

该模型患者belongs_to FeedList,其中has_many患者。我试图创建一个新的FeedList,我想将当前在数据库中的所有患者添加到FeedList中。我目前正在尝试在feed_lists_controller.rbcreate之内执行此操作。如何将一个模型实例添加到另一个Rails实例中

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

这对我来说看起来很好。 – Jason

+0

请参阅编辑,它似乎没有工作@jason –

+1

创建操作不是每次创建模型实例时都会调用的回调函数,它是一个控制器操作,只要访问与其关联的路由它。至少,通常是这样设置的。这个创建功能在哪里? – Jason

回答

2

尝试在你的FeedList模型文件使用callback

after_create :add_patients 

    private 
    def add_patients 
     Patient.all.each do |p| 
     self.patients << p 
     end 
    end 

贾森上面“创建行动[即在控制器]提到是不是被调用每次创建实例时回调一个模型”。有关回拨是什么的信息,请参阅What is a callback function?after_create回调本质上说要调用add_patients后立即致电FeedList.create

+0

谢谢,我现在就试试。你能向新手解释什么是“回调”,为什么你必须在顶部放置'after_create:add_patients'? –

+0

@VincentRodomista查看我的编辑 – kshikama

+1

回调是一种通用编程术语,用于在代码完成某些操作时运行的函数,如读取文件,打开视频流或创建数据库记录。 – Jason

相关问题