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 =开发者_如何学C> 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?
Tried replacing build_conversation
with create_conversation
?
精彩评论