ActiveRecord:创建实例后添加外键

时间:2015-05-26 14:59:42

标签: ruby-on-rails activerecord rails-activerecord

我希望在创建实例后创建一个外键“rails way”。它是如何工作的?

型号:

class Letter < ActiveRecord::Base
  belongs_to :sender
  belongs_to :campaign
end

class Campaign < ActiveRecord::Base
  has_many :letters
end

class Sender  < ActiveRecord::Base
  has_many :letters
end

代码:

sender1 = Sender.first
letter1 = sender1.letters.create

#Now I want to add a connection from letter1 to a campaign, 
#but this cannot be the proper rails way:
letter1.campaign_id = 1

0 个答案:

没有答案