How do I update a list after the action of a remote form with AJAX?

4

I'm having a problem I've never had in Java but I'm almost going crazy in Rails. I'm developing a project where there are users and groups. So I created a separate model for N:N relationship between users and groups.

In the group show page I created the group description, just below the form part _groupsuser appears to allow the creator of the group to add users to that group. Below all this I rendered the partial to display the list of users belonging to the group.

The project has a somewhat different structure because I'm using partials to avoid repeating the same logic in the control and in the view so I'd like to avoid moving the structure and focus only on updating the listing once it has the% %. In the case I created in the control the method create:

def create
    if group.user == current_user       
        @groupsuser = Groupsuser.new(groupsuser_params)
        @groupsuser.group = group
        if @groupsuser.save
            flash[:notice] = 'User was successfully add.'
        else
            flash[:alert] = 'User cannot be add.'
        end
    else
        flash[:notice] = "You didn't have permition."
    end
    head :ok
end

I would like to do the update using just ajax similar to the java update method with facelets type:

    <p:commandButton value="All" id="btnAll" process="@all" update="grid"   
                actionListener="#{personBean.savePerson}"/>

For example:

$('create_button').onClick('ajax:complete', render(@group));

to refresh the entire page or

$('create_button').onClick('ajax:complete', "Comando mágico para atualizar apenas a div");
    
asked by anonymous 03.02.2014 / 19:44

1 answer

1

First of all, study the Cancan gem to implement the permissions.

With Cancan, the code for your method would look like this:

def create
    @groupsuser = Groupsuser.new(groupsuser_params)
    @groupsuser.group = group
    if @groupsuser.save
        flash[:notice] = 'User was successfully add.'
    else
        flash[:alert] = 'User cannot be add.'
    end
end

Now to make the user registration for Ajax, first add the remote: true option to your registration form. With this, you do not need to add JS code to the POST form with Ajax.

Then, add the code to the end of the action create. This code indicates that the request will be of type javascript .

respond_to do |format|
    format.js
end

Lastly, create the view create.js.erb, which contains the JS code that should be executed in the request response. It should be something like:

$('div#users-container').html('<%= j render(@group.users) %>');

With this code, it is not necessary to add JS listener "on hand". The remote: true option is available through the jquery_ujs library.

    
04.02.2014 / 13:27