Rails: create through-record via association

徘徊边缘 提交于 2019-12-12 14:56:21

问题


If anyone has a better title, please let me know :p

I have the following models:

class Car
  has_many :car_drivers
  has_many :drivers, :through => :car_drivers
end

class Driver
  has_many :car_drivers
  has_many :cars, :through => :car_drivers
end

class CarDriver
  belongs_to :car
  belongs_to :driver
end

Now I want to create a new Driver via Car, but the record in the join-table (car_drivers) should be created as well. I tried the following, but while the car record is created, the join-table record is not: driver_object.cars.create

What is the best practice in this case?


回答1:


The following is going to create new instance of Car, but does not associate it with the Driver instance.

driver_object.cars.create

The following works

driver_object.cars << Car.create(...)

The << method in ActiveRecord appends the newly created Car instance to the :cars collection on Driver and calls save on Driver, creating the CarDriver instance to relate the new Car with driver_object.



来源:https://stackoverflow.com/questions/12654040/rails-create-through-record-via-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!