So I have a Conversation model, which has_many messages. I’m trying to create a new message when I create a conversation. Here’s my ConversationsController:
class ConversationsController < ApplicationController
before_filter :authenticate_user!
def new
recipient = User.find(params[:user])
@conversation = Conversation.new(from: current_user, to: recipient)
@conversation.messages.build(from: current_user, to: recipient)
end
def create
@conversation = Conversation.create(params[:conversation])
redirect_to @conversation
end
end
And here’s my form (conversations/new.html.erb):
<%= form_for @conversation do |f| %>
<%= f.fields_for :messages do |g| %>
<%= g.label :subject %>
<%= g.text_field :subject %>
<%= g.label :content %>
<%= g.text_field :content %>
<% end %>
<%= f.submit "Send" %>
<% end %>
The problem: when I submit the form, the conversation’s message gets saved, but the to and from fields that I specified as parameters in build are not saved (they are nil). However, the subject and content fields filled out in this form are saved just fine.
I’ve done a little bit of digging… if I do a puts on @conversation.messages in the new action, or in the new.html.erb, the message seems to have to and from. It’s only when the message reaches the create action do those fields disappear.
UPDATED:
You may still want to validate the recipient in your Conversation model.