如何在Rails中将模型实例添加到另一个实例中

时间:2015-11-28 21:14:32

标签: ruby-on-rails

模型患者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

我是在正确的轨道上吗?

1 个答案:

答案 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