1

Looked at a number of resources and can't seem to figure this out.

I am working on a messaging system based on this code by BinaryMuse:

https://github.com/BinaryMuse/so_association_expirement/compare/53f2263...master

It doesn't have a respond feature, so I'm trying to build it.

I added the following code to the UserConversations controller:

def update
    @user = User.find params[:user_id]
    @conversation = UserConversation.find params[:id]
    @conversation.user = current_user
    @message = @conversation.messages.build
    @message.conversation_id = @conversation
    @message.save
    redirect_to user_conversation_path(current_user, @conversation)
end

And the following to the UserConversations#show view:

<%= form_for(@conversation) do |f| %>
<%= f.fields_for :messages do |m| %>
    <div>
        <%= m.label :body %><br />
        <%= m.text_area :body %>
    </div>
<% end %>
<%= f.submit %>

With what I have, a new message with the correct conversation_id is created. However, it has no body or user_id attached to it.

Any ideas what I'm doing wrong?

Thanks in advance for your help!

jon
  • 170
  • 1
  • 13

2 Answers2

1

BinaryMuse (the creator of the original code I was working with) was awesome enough to look at his old code and add a bit to cover replies. How great is that? Here is the link to his stuff:

Message System with Reply

P.S. Thank you to Patrick as well, I definitely appreciated the insight!

jon
  • 170
  • 1
  • 13
0

These lines create your new message with the correct conversation_id. Your problem arises from not involving the parameters passed in on your form.

@message = @conversation.messages.build
@message.conversation_id = @conversation
@message.save

Ideally you would want do something like

def update
    @user = User.find params[:user_id]
    @conversation = UserConversation.find params[:id]
    @conversation.user = current_user
    if @conversation.update_attributes(params[:conversation])
        redirect_to user_conversation_path(current_user, @conversation)
    else 
        render(:action=>'edit')
    end
end

Let the update_attributes handle updating the 'messages.' Make sure you have accepts_nested_attributes_for specified in the Conversation model.

For more info I'd take a look at