Forum: Ruby on Rails 2.3 Nested Model Forms; build new without updating existing

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Edf24769a4b5466a21c9cea58856ce26?d=identicon&s=25 Guitaronin (Guest)
on 2009-05-12 12:07
(Received via mailing list)
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.
Edf24769a4b5466a21c9cea58856ce26?d=identicon&s=25 Guitaronin (Guest)
on 2009-05-14 22:36
(Received via mailing list)
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.
548dde5574b950a8ac2f09cb0ee681d5?d=identicon&s=25 Andrew France (Guest)
on 2009-05-19 00:49
(Received via mailing list)
Hi,

On May 12, 9:43 am, Guitaronin <arianr...@gmail.com> 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
This topic is locked and can not be replied to.