开发者

Rails - Creating Parent & Nested Model Records?

I have two models:

class Conversation < ActiveRecord::Base
    has_many :conversation_participations
end

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

Right now I make records by doing something like:

  @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

The problem with this is I need the conversation_pa开发者_StackOverflow中文版rticipations to all save at the same time, not one at a time. How can I do this with Rails? Build a conversation and partipiations and save all at once?


conversation_participations is either an UPDATE, or an INSERT. There's no determining that until the code actually runs. And even then, some databases may lack support for multiple inserts.

What you want sounds like a transaction. A transaction can be created in Rails using the transaction method of any model, which takes a block. (And it doesn't really matter which model you call it on, it applies to any database operations within that block.)

Basically:

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

You'll want to make sure your database supports transactions. You didn't specify which database system you're using, but MySQL, for example, turns transactions into no-ops for the MyISAM backend. If you're using MySQL, make sure your tables are InnoDB. (I believe if your tables were created using Rails, they will be, but best double check.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜