问题描述:

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:

class ConversationsController < ApplicationController
  before_filter :authenticate_user!
  def new
    recipient = User.find(params[:user])
    @conversation = Conversation.new(to: recipient)
    @conversation.messages.build
  end

  def create
    @conversation = current_user.conversations.build(params[:conversation])

    # Set all the attributes for conversation and messages which
    # should not be left up to the user.
    @conversation.to = current_user
    @conversation.messages.each do |message|
      message.to = @conversation.to
      message.from = @conversation.from
    end

    redirect_to @conversation
  end
end

<%= form_for @conversation do |f| %>
  <%= f.hidden_field :recipient %>
  <%= 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 %>

You may still want to validate the recipient in your Conversation model.

相关阅读:
Top