문제

I have a requirement when creating a new Foo object and a unique field foo_id exist already, I have to redirect to the edit page for that foo_id. I'm using jQuery autocomplete with the foo_id textbox already and was wondering what the best way to do this?

My initial thought is to return an extra isExist attribute in the JSON that gets returned to jQuery autocomplete and based onselecting a foo_id, I'll check the isExist attribute and redirect. Is there a better way to do this? Also, if I need to do a redirect from JavaScript, should I generate the path from Rails?

도움이 되었습니까?

해결책 2

There are a lot of ways to do this, but an easy way would be to send an ajax GET request (on the change event for the autocomplete) with the id of the selected Foo instance to a controller endpoint. Do a lookup with the id. If an instance with the id exists, return a 200; otherwise, return a 404. So you would have success and error handlers respectively to handle those cases.

At this point, you can do many more things. Your REST endpoint could send the result of foo_path(foo) (remember you looked up foo) in the body of the 200 response. You could keep a list on the client side of all the different foo_path(:id)s corresponding to the choices in your autocomplete and pick the right one on success. Either way, you can then set document.location in your JavaScript to the correct path.

And probably a lot of other things others will point out I'm sure.

다른 팁

Based on Vidya's answer and found results from other questions, this is what I did:

in Foo's controller added:

  def checkFooExists
    @foo = Foo.find_by_foo_id params[:foo_id]
    if !@foo.nil?
      flash[:notice] = 'You entered an existing Foo ID, so here is the edit page'
      flash.keep(:notice)
      render :js => "window.location = '" + edit_foo_path(@foo) + "'"
    else
      render :nothing => true, :status => 409      
    end  
  end

in routes change:

  #resources :foos
  resources :foos do
    collection do
      get 'checkFooExists'
    end
  end

in application.js, in the autocomplete event handler for select for textbox add one jQuery get line:

        select: function(event, ui) {
            $.get("/foos/checkFooExists", { foo_id: ui.item.foo_id });
            $('#bar').val(ui.item.bar);
            return false;
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top