0

I am very new to rails and having a bit of a problem with a simple page I am putting together for learning and I was hoping someone might have some suggestions on a fix or a better approach.

Essentially, I have the concept of a scratch pad. Each pad has_many tasks and has_many notes. In the pad's show, I want to have two independent forms. One for adding tasks and one for adding notes. The problem is, I build the forms like so:

<%= form_for([@pad, @pad.tasks.build]) do |f| %>
    <%= f.text_field :text %> <%= f.submit %>
<% end %>

Now, since I've called .build, when I later call the below code to render the tasks it always renders an additional, empty record in the list.

<ul>
    <%= render @pad.tasks %>
</ul>

I thought about using a nested form, but this seems to require me to use PadsController::Update rather than TasksController:Create like I want to.

What would be the appropriate approach in this situation? Being so new to rails (started yesterday), I'm afraid I'm missing something obvious.

Edit: I added the source to a github repository. As I said, this is just a learning project for me. https://github.com/douglinley/scratchpad

spacemunkee
  • 216
  • 1
  • 2
  • 8

2 Answers2

0

If you simply want a new task without it being added to @pad.tasks collection, I believe you can just do @pad.tasks.new instead of @pad.tasks.build (which does add it to the collection).

For more on build vs new, check out Build vs new in Rails 3

Community
  • 1
  • 1
Tyler
  • 11,272
  • 9
  • 65
  • 105
  • Thanks for the response. According to that article, it appears that Build and New are now pretty much the same (post 3.2.3) and they both add the new record to the collection. This is what I'm trying to avoid. – spacemunkee Jul 21 '13 at 17:28
0

So, this was much easier than I thought. Instead of calling new on the collection, I just created a new object for the form. Example below:

<%= form_for([@pad, Task.new]) do |f| %>
    <%= f.text_field :text %> <%= f.submit %>
<% end %>
spacemunkee
  • 216
  • 1
  • 2
  • 8