how to add records to has_many :through association in rails

前端 未结 3 799
醉话见心
醉话见心 2020-11-30 17:34
class Agents << ActiveRecord::Base
  belongs_to :customer
  belongs_to :house
end

class Customer << ActiveRecord::Base
  has_many :agents
  has_many :ho         


        
3条回答
  •  鱼传尺愫
    2020-11-30 18:07

    I think you can simply do this:

     @cust = Customer.new(params[:customer])
     @cust.houses << House.find(params[:house_id])
    

    Or when creating a new house for a customer:

     @cust = Customer.new(params[:customer])
     @cust.houses.create(params[:house])
    

    You can also add via ids:

    @cust.house_ids << House.find(params[:house_id])
    

提交回复
热议问题