【问题标题】:Rails - Creating Parent & Nested Model Records?Rails - 创建父和嵌套模型记录?
【发布时间】:2010-11-25 02:17:46
【问题描述】:

我有两个模型:

class Conversation < ActiveRecord::Base
    has_many :conversation_participations
end

class ConversationParticipation < ActiveRecord::Base
  belongs_to :user
  belongs_to :conversation
end

现在我通过以下方式制作记录:

  @conversation = Conversation.create(......)
  conversation = @conversation.save

   params[:users].each do |user|
     @user = User.find(user.to_i)
     conversation_participation = @recipient.conversation_participations.find_or_create_by_conversation_id(@conversation.id)
     conversation_participation.save
    end

这样做的问题是我需要同时保存所有的 conversation_participations,而不是一次保存一个。我怎样才能用 Rails 做到这一点?建立对话和参与并一次保存所有内容?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    conversation_participationsUPDATEINSERT。在代码实际运行之前无法确定。即便如此,某些数据库可能仍缺乏对多次插入的支持。

    你想要的听起来像是一笔交易。可以使用任何模型的 transaction 方法在 Rails 中创建事务,该方法需要一个块。 (并且调用它的模型并不重要,它适用于该块中的任何数据库操作。)

    基本上:

    Conversation.transaction do
      @conversation = Conversation.create(......)
      # ...etc...
    end
    

    您需要确保您的数据库支持事务。您没有指定您正在使用哪个数据库系统,但是 MySQL,例如,将事务转换为 MyISAM 后端的无操作。如果您使用的是 MySQL,请确保您的表是 InnoDB。 (我相信如果您的表是使用 Rails 创建的,它们会是,但最好仔细检查。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多