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.