lmost1
lmost1

Reputation: 35

Ruby on Rails: how to create an object without switching the view

I am incredibly new to rails, so I think my questions is pretty simple. I essentially have an object submit button on a view page (so runs create and save for the specified object) but on selecting the button I don't want the view to change at all (so just stay with the same page that was already loaded). I'm having trouble editing the create action in my object controller so that nothing happens to the view (is this even possible? or is the idea that a new view must occur for every action).

Thanks for all your help! Lisa

Upvotes: 0

Views: 871

Answers (3)

John Furtado
John Furtado

Reputation: 555

This can be done by creating an action in the controller,

class YourController < ApplicationController

   def index
   end

   def youraction
   end
end

,then set a route to it in the routes.rb

and then simply set your form to point to that url and add the

remote: true

option to the form tag.

Upvotes: 1

Edward
Edward

Reputation: 1914

You can do this by using ajax request:

in your controller create an action that does the job of creating the object you want:

class SomeController < ApplicationController
  def index
    #this is your view controller
  end

  def youraction
    #create an object
    render :nothing => true
  end
end

and then bind your button with a javascript function that does the ajax request:

HTML

<button id="submit_button">Submit</button>

Javascript

$(document).ready(function (){
  $('#submit_button').click(function(){
    $.ajax({
      url: 'url_to_the_controller/youraction',
      type: 'POST'
      success: function (){
        alert('success');
      },
      error: function (){
        alert('error');
      }
    });
  });
}

Upvotes: 1

Wasi
Wasi

Reputation: 1246

So you want to store the object and you dont want the URL to change.

In your create action, after the object is saved. Redirect to that view.

so something like:

$   if @object.save
    redirect_to :action => "index"
    # or
    # redirect_to object_path # you can set this in config/routes.rb
    # or
    # redirect_to :action => "show", :id => @object.id

Upvotes: 1

Related Questions