views:

39

answers:

2

In my rails app, I want to have a sortable list as part of an object creation. The best practice suggested in Railscast adds the acts_as_list plugin and then initiates AJAX calls to update item position. However, AJAX calls won't work on an unsaved model, which is the situation with new.

One solution would be to save the model immediately on new and redirect to edit. This would have a nice side effect of persisting any change so the user could resume work should he be interrupted.

However, this solution adds the unwanted complexity of saving an invalid model, compromising rails' validation processes. Is there any better way to allow AJAX + validations without going into too much work?

+1  A: 

Your new action has the same access to parameters that any other action has. You could pass parameters for the unsaved object back to the new action and an object re-initialized with attributes set could be returned back to the view. For instance:

controller:

class WidgetsController < ApplicationController
  def new
    @widget = params.has_key?(:widget) ? Widget.new(params[:widget]) : Widget.new
  end
  ..
end

Then in your view you'd have to send params to the new action via a link or a form post.

Patrick Klingemann
Just to make sure I understand: After I make the AJAX call to "new", do I have to run some sort of JS logic to update the page? Would it be simpler than implementing a client-side caching of the "position" attribute?
shmichael
Not necessarily, RJS could handle that for you. For instance, if you use link_to_remote, and pass the DOM ID you're updating to the :update option, whatever is returned from the new action will be placed in the element with that DOM ID on the page.
Patrick Klingemann
A: 

you can temporary store unsaved object in a 'session'.

like (this code must be in controller)

my_model = MyModel.new(params[:my_model])
session[:my_model_tmp] = my_model
zed_0xff