简体   繁体   中英

Rails: parent build_association in a callback

Developing a custom messaging system (yeah, I know...yet another one of those).

I have:

class Conversation << AR::Base
  has_many :messages
end

class Message << AR::Base
  belongs_to :conversation

  # this is what I want, create a conversation if one isn't assigned
  before_create :assign_to_conversation, :unless => :conversation

  def
    # but this won't save parent association
    build_conversation(:subject => subject, :starter => user)
  end
end

Basically, I want to be able track messages as part of a conversation. If a user sends a new msg, it should become part of a new conversation. If a msg is a reply to an existing convo, I just want to assign the message to that particular conversation.

In messages_controller I wish to just do

def create
  @message.save(params[:message]).
end

Without having to go with

def create
    transaction do
      c = Conversation.build(...)
      c.messages.build(params[:message])
      c.save
    end
end

I'm trying to keep my controllers simple and also conduct conversation and message creation as part of a single transaction.

I think I figured it out.

Instead of before_create i know have

before_validation :assign_to_conversation, :on => :create, :unless => :conversation

Everything appears to work now. And all is wrapped up in a transaction.

Any thoughts?

试图用create_conversation替换build_conversation吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM