0

我有关联的模型UserChannelRails 3 应用程序。Channel是在创建的那一刻User创建的

class User < ActiveRecord::Base
  before_create do
    self.channels.build
  end
  has_many :channels  
end    

class Channel < ActiveRecord::Base
  belongs_to :user
  validations block
  ...
end

问题是如果 Channel 的验证不通过User,将在 DB 中创建,但Channel不会。在哪个回调位置Channel创建创建UserChannel在一个“事务”中创建?或者,也许,还有另一种正确的方法?

提前致谢。

UPD1: ChannelUser模型中创建时自动创建,因为在某些情况下创建的对象不调用控制器。

4

3 回答 3

2

您可以使用“accepts_nested_attributes_for”

class User < ActiveRecord::Base
has_many :channels
accept_nested_attributes_for :channels
end

class Channel < ActiveRecord::Base
belongs_to :user
validations block
end

于 2013-04-16T07:39:55.163 回答
1

使用validates :channels, associated: true.

您可能应该查看您的频道验证,因为如果它没有保存,那么您正在做您的应用程序没有预料到的事情。

于 2013-04-16T07:32:54.567 回答
1

你想太多。这是非常常见的情况,并且有一个约定。

首先在 Pedro 说,您需要在 Channel 模型中验证关联。这将防止在没有 user_id 的情况下保存频道。

然后,在控制器的create操作中,您只需确保将包括用户对象在内的所有参数发送到此处以进行创建。

于 2013-04-16T07:36:34.453 回答