has_many:通过不创建我的第三个模型

时间:2015-08-27 20:02:27

标签: ruby-on-rails associations has-many-through model-associations

我正在构建基于位置的应用程序,并注意到一些奇怪的行为。我的模型如下:

class User < ActiveRecord::Base
has_many :attendances, dependent: :destroy
has_many :events, through: :attendances

class Event < ActiveRecord::Base
acts_as_mappable :lat_column_name => :latitude,
                 :lng_column_name => :longitude

has_many :attendances, dependent: :destroy
has_many :users, through: :attendances

class Attendance < ActiveRecord::Base
belongs_to :user
belongs_to :event

所以问题是,在创建新事件时,我首先拥有user.events.new(params)然后我有一个if语句来检查新事件是否被正确保存,所以if event.save #do stuff.当我这样做时,未创建将Attendance连接到新创建的user的{​​{1}}模型,而如果我event已成功创建新user.events.create(params),。这是正常的吗?在这种情况下我是否必须使用Attendance?为什么我在user.events.create然后Attendance时创建了新的user.events.new

编辑:从event.save添加Create方法:

events_controller.rb

2 个答案:

答案 0 :(得分:2)

此行为是预期的,这是一个众所周知的问题。幸运的是,它有一个解决方案。尝试将inverse_of参数添加到belongs_to关联:

class Attendance < ActiveRecord::Base
  belongs_to :user, inverse_of: :attendances
  belongs_to :event, inverse_of: :attendances
end

您可以在此处详细了解此问题:Link

解决方案2:

您也可以将控制器代码更改为:

  event = Event.new(...event_params...)
  if event.save
    user.events << event
    render :json => {...}
  else
    ...

答案 1 :(得分:0)

通常我会在模型中使用accepts_nested_attributes_for。然后使用.build方法将它们保存在创建操作中。

这里有一些链接可能对您有所帮助: Association MethodsRails Casts: Nested Forms(这是对accepts_nested_attributes_for方法的一个很好的解释。)

希望有所帮助

相关问题