Re: Creating Variable Number of Models in One Form

great post. i have a question though:
when i submit the form, nothing gets saved.
when i look at the source for the page, for form looks like this:

<form action="/projects" method="post">

which looks like its missing something ( the :action part?), but maybe its some kind of new routes devilry.

also, you might want to mention something about setting up the map.resource :projects because the new.rhtml uses that projects_path shortcut... not being up to speed on this REST stuff i had to go searching around to find out what was going on

Last edited by pleatherrebel (2006-11-29 16:48:03)

Re: Creating Variable Number of Models in One Form

Oops, it wasn't my intention to have REST specific stuff in this tutorial. I forgot to change that in the last code example. Thanks for pointing it out. I'll work on updating it.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

any idea why mine isn't posting any data to the database? i did freeze:edge yesterday. do i need some plug-in?
i got it to work by usign :url => {:action = "create" }
instead of the other thing

Last edited by pleatherrebel (2006-11-30 14:58:22)

Re: Creating Variable Number of Models in One Form

Hmm, I'm not sure why it isn't saving. Is the create action being called? Check out the development.log file to see what's being called along with the generated queries.

The way REST works is it will automatically call the "create" action if the page is called using POST. In fact, seeing that it is working when setting :action => 'create' makes me wonder if the installed edge rails is actually being used. Go here to see what version of Rails is being used: http://localhost:3000/rails_info/properties

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

I can't get to that page because the app is on a different machine, but in vendor/rails it says REVISION_5650

Re: Creating Variable Number of Models in One Form

I'm just wondering if edge rails is actually being used. Try commenting this line in environment.rb if it exists:

RAILS_GEM_VERSION = '1.1.6'

I'm not sure if that will change anything, but worth a try.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

Now its working. Both with and without that line commented out. Oh well. Thanks for the thread. I have given up on figuring out variable number of text-fields forms.

Re: Creating Variable Number of Models in One Form

Do you think it would be possible to do this?
Say you want to add a bunch of very similar tasks. You fill the fields for one task, then hit a 'duplicate' link, and  then the fields for another task appear auto-filled with the info from the first task. Then you only have to edit a field or two from the duplicated rows instead of typing everything out for each row.

Re: Creating Variable Number of Models in One Form

Yeah, I imagine that is possible. If you pass the index of the fields you want to duplicate through the link_to_remote parameters, you can assign the new fields with the value of the old fields. Maybe something like this in RJS:

# after rendering the new partial
page["tasks[#{params[:index]}]_name"].value = "$('tasks[#{params[:source_index]}]_name').value"

Completely untested, but I think that will assign the value of the original task to the value of the new task you just created. There's probably a better way to do this, but at the moment I'm at a loss.

The hard part will be passing the new "index" parameter. Right now we update the link every time we add a task, but now each task will have a link, so it might become tricky to update every single link. At this point you might want to store the current index in the session so you can have access to it without passing the value back and forth.

I'm just kind of thinking out load here, so let me know if it doesn't make sense.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

I am having the following problem.  I've constructed my form using more or less the same code as in your tutorial to create a page that has_many paragraphs.  Each paragraph belongs_to :page and validates_presence_of :page.

When I try to save, I get the following error: "Validation failed: Paragaphs is invalid, Paragraphs is invalid" (assuming that I had added two paragraphs).

Somebody else seems to be having the same problem at http://rails.techno-weenie.net/forums/1 … 685?page=1.  Is it an error in my code, or is rails not actually magic enough to pull this off without saving the page before calling build?

Re: Creating Variable Number of Models in One Form

I'm assuming you mean validates_presence_of :page_id. Yes, this is a known problem as is mentioned in the thread you linked to. Unfortunately, it does not have a good work around. It may be fixed in 1.2 but I haven't done extensive testing.

Anyway, you may need to save the Paragraph models separately to avoid this error. I can probably post some code to do that if you need it.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

yes, that is exactly what i meant.  I can write the code, it just kind of bugs me so i was hoping there was a more "elegant" way.  In any case thanks very much for your excellent tutorial!

Re: Creating Variable Number of Models in One Form

In conclusion, if your task model :validates_presence_of :project_id, just add the following line:

def create
  @project = Project.new(params[:project])
  @project.save  # Add this line.  Voila!
  params[:tasks].each_value { |task| @project.tasks.build(task) }
  if @project.save
    redirect_to :action => 'index'
  else
    render :action => 'new'
  end
end

Not exactly rocket science but what can I say, I like the sound of my own voice.
Also: this would be easier to debug if the save method recorded failures in the log.  Oh well.

Re: Creating Variable Number of Models in One Form

One thing to watch out for is if one of the task validations fail, this will result in the project being saved while the tasks are not saved.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

Hi Ryan, wonder if this thread is closed?
because I'm having an extended problem - How can I handle multiple dates? My challenge: I want to show a list of tasks together with their due_dates and I only want to be able to update the dates (with text_field and calendar helper) and on submit the modified dates (or all) shall be updated  - any suggestions highly appreciated..

Re: Creating Variable Number of Models in One Form

In my example I just used a text field for editing the given task's "name" attribute, but you could easily use any kind of field (such as date_select) to edit some other attribute (due date).

While this thread is not closed, I prefer you create a new thread providing the code you currently are using and describing what specifically isn't working.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

Hello Ryan,

this tutorial saved my life since I am absolutly a newbie with ruby and rails and this article is exactly what I need for my project! But unfortanely there are two things I can't explain to myself:

First, in your example you put a first task into the project when creating a new one

@project.tasks.build # creates just one task

but this one never appears in my project. Even if I would try something like

10.times {@voucher.positions.build}

there is still no task ('position' in my case) until I add the first one. Do you (or anybody else) have an idea what the problem could be?


The second problem is that error which occurs on pushig the create button:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.each_value

def create
  @voucher = Voucher.new(params[:voucher])
   
  # vvv  the error occurs in this line  vvv
  params[:positions].each_value do |position|
    @voucher.positions.build(position) unless position.values.all?(&:blank?)
  end
  if @voucher.save
    flash[:notice] = 'Voucher was successfully created.'
    redirect_to :action => 'list'
  else
    render :action => 'new'
  end
end

This part is taken from the previous article and before I made the new changes it worked for me without any problems. It seems to me that any reference to params[:positions] is getting lost and I cant' figure out why. I have to say that my code is nearly the same as the one from this tutorial except for 'project' changed to 'voucher' and 'task' to 'position'.

I would really appreciate on any help or hint!

Thanks in advance

Re: Creating Variable Number of Models in One Form

Ok, forget the second part. Of course this is a result of the first problem. I pushed the create button without adding any position. Sometimes one should think about it before posting #roll#

Re: Creating Variable Number of Models in One Form

Not sure what the problem is, can you post the code you are using in the new.rhtml view? Specifically this area:

# in new.rhtml
<% @project.tasks.each_with_index do |task, index| %>
  <%= render :partial => 'task_fields', :locals => { :task => task, :index => index } %>
<% end %>

Make sure you aren't missing an equal sign when rendering the partial or something.

Railscasts - Free Ruby on Rails Screencasts

Re: Creating Variable Number of Models in One Form

Of course your are right, there was missing an equal sign. Unbelievable. But now I'm really confused since the problem still remains. So, here is the new.rhtml:


<% form_for :voucher, :url => { :action => "create" } do |f| %>
  <%= render :partial => 'form' %>
  <%= render :partial => 'add_position_link', :locals => { :index => @voucher.positions.size } %>
  <br>
  <div id="positions">
    <% @voucher.positions.each_with_index do |position, index| %>
      <%= render :partial => 'position', :locals => { :position => position, :index => index } %>
    <% end %>
  </div>
  <p><%= submit_tag "Create" %></p>
<% end %>
<br><br>
<%= link_to 'Back', :action => 'list' %>