2.3 Nested Model Forms; build new without updating existing


#1

I’m trying to build something similar to a Facebook messaging app, in
which the view displays all the messages for a particular thread, with
a form box for replying at the bottom of the thread.

The problem is that using fields_for generates form fields for each
existing record, and for one new record. In this case, there is no
need to edit existing messages - just a need to add new messages.

Does anybody know how to do this? Code is below.

Models:
class MessageThread < ActiveRecord::Base
has_many :messages
accepts_nested_attributes_for :messages, :allow_destroy => true
end

class Message < ActiveRecord::Base
belongs_to :message_threads
end

View (show.html.erb)

<% @message_thread.messages.each do |message| %>
<%= message.message %>
<% end %>

<% form_for @message_thread do |thread_form| -%>
<% thread_form.fields_for :messages do |message| %>
<%= message.label :message %>
<%= message.text_field :message %>
<% end %>

<%= submit_tag ‘Send Message’ %>
<% end -%>

Thanks.


#2

I just wanted to follow up with my simple (maybe obvious) solution…

<% form_for @message_thread do |thread_form| -%>
<% thread_form.fields_for :messages do |message| %>
<% if message.object.new_record? %> # The magic!
<%= message.label :message %>
<%= message.text_field :message %>
<% end %>
<% end %>

Duh! If there’s a smarter way, I’m still listening.


#3

Hi,

On May 12, 9:43 am, Guitaronin removed_email_address@domain.invalid wrote:

The problem is that using fields_for generates form fields for each
existing record, and for one new record.

The ‘new record’ is behaviour I’m unaware of! I think that you have to
build the new record in the association.

end
<%= message.text_field :message %>
<% end %>

Nested attributes fields_for supports setting an explicit object as
the second parameter, like so:
<% thread_form.fields_for(:messages, Message.new) do |message| %>

Although the proper way would be to set @new_message or similar in the
controller and pass that, or thread_form.object.messages.build().

Hope that helps,
Andrew