Delete / Modify database records from EditorGrid panel - ruby-on-rails

I am using ExtJs with Rails 3.x . How to delete/modify records from EditorGrid using Ext.Ajax.request method?
I tried using store.remove() and similar other methods but it doesn't remove record from database.
Thanks in advance !!
Code :
//** Destroy method **//
def destroy
puts 'destroy'
#unit = Unit.find(params[:id])
puts 'will destroy'
#unit.destroy
puts 'destroyed'
end
//** units.js **//
var delbtn = Ext.getCmp('btnDelete');
delbtn.on('click',function(){
var grid = Ext.getCmp('maingrid');
var selection = grid.getSelectionModel().getSelected();
Ext.Ajax.request({
url: '/units/destroy',
method: 'POST',
params: {
'id' : selection.data.id }
});
});//end del function
//** Store.js **//
Ext.data.Api.restActions = {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE' };
storeId: 'MyUnitStore',
root: 'data',
autoLoad: true,
autoSave: false,
//batch: true,
restful:true,
writer: new Ext.data.JsonWriter({
encode : false,
listful:false,
destroy: '/units/destroy',
update : '/edit'
}),
url: '/units.json',
fields: [
{
name: 'unitname'
},
{
name: 'description'
}
]
//** Edit Button **//
var store = Ext.getCmp('maingrid').getStore();
store.update();

store.remove() removes the data (record) from your grid's associated store only. It does not communicate with server side by itself. You need to use the Ajax request and communicate with Rails 3.x to get the appropriate record deleted.
var selection = grid.getSelectionModel().getSelected();
Ext.Ajax.request({
url: '/ExampleController/Delete',
method: 'POST',
params: {
'id': selection.data.id
},
success: function(result, request){
// Refresh the grid store and display
},
failure: function(result, request){
// Display delete error message
}
}

Related

How to reload particular partial value with response from rails api?

I have set up a rails api and it only response in the following format which is done through the serializer:
data: { user_name: 'Test User' }
And on the view side, I have got the following partial:
.user-change
= render partial: 'test_user', locals: {user_name: current_user.name}
What would be the correct way to change the user_name as per the API response from the following successful ajax request?
$("#change-me").click(function() {
var user_id;
user_id = $("#user_id").val();
$.ajax({
url: "/api/v1/user/change/" + user_id,
method: "POST",
dataType: "json",
data: JSON.stringify({
{
user_id: user_id,
}
}),
success: function(res, status, xhr) {
let response = res.data;
let userName = response.user_name;
// Update user_name after this event on the partial?
}
},
error: function(res) {
}
});
})
Partial code: _test_user.html.haml
.col-md-9
%p= "Hi! This is the request change from #{user_name}."

Remote Validation with Knockout in MVC 4, Allowing invalid data to save

Hi there I am using remote validation with knockout validation rules to check if a client is booked at the same time as the proposed date. I finally got the viewmodel sending data to the controller validation method and the method does return a true or false however i began to notice that the call back was not stopping the user from saving if the client is not valid.
I found this by swapping the conditions and allowing the controller method to return false I debugged the client side and found that the call back variable was in fact false but i was not receiving an error messae nor was it stopping m from saving the appointment.
My question is am i missing a piece of code that allows this or is there a bug that i am missing?
Viewmodel rule validation:
ko.validation.rules['validateClientasync'] = {
async: true,
message: 'Client is already booked in at this time!',
validator: function (val, parms, callback) {
var defaults = {
url: '/Appointments/CheckClient/',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
callback(/* true or false depending on what you get back in data */);
}
};
if (parms.data != undefined && parms.data.appointment != undefined) {
var appointment = ko.toJS(parms.data.appointment);
$.ajax({
url: '/Appointments/CheckClient/',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: ko.toJS(parms.data.appointment),
success: function(data) {
callback(/* true or false depending on what you get back in data */);
}
});
}
}
};
ko.validation.registerExtenders();
self.appointment = {
id: appointment.id,
start: ko.observable(appointment.start),
end: ko.observable(appointment.end),
text: ko.observable(appointment.text),
clientid: ko.observable(appointment.clientid).extend({
validateClientasync: {
data: self
}
}),
employeeid: ko.observable(appointment.employeeid),
roomid: ko.observable(appointment.roomid),
fee: ko.observable(appointment.fee).extend({min: 10})
};
according to the definition in https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Async-Rules, just put a json there would be enough, like:
callback(
{
isValid: true //true or false with json format returned from the validation method in your controller,
message: "your cusotm error message here"
}
);

How to send params from nested forms?

I'm making a POST request from a nested form which is written in reactjs such that it is making an ajax request to create method of the products controller.
React Code:
I have an empty object in the getInitialState like this
getInitialState: function() {
return {
products: [{name: '', price: '', quantity: ''}],
count: 1
};
},
When i submit the form,
handleSubmit: function(e) {
e.preventDefault();
var productsArray = this.state.products;
$.ajax({
data: {
product: productsArray
},
url: '',
type: "POST",
dataType: "json",
success: function ( data ) {
console.log(data);
// this.setState({ comments: data });
}.bind(this)
});
},
the object gets populated and the parameter hash becomes like this
Parameters: {"product"=>{"0"=>{"name"=>"", "price"=>"", "quantity"=>""}}, "shop_id"=>"gulshop"}
So i'm getting
ActiveRecord::UnknownAttributeError (unknown attribute '0' for Product.):
How can i get the parameter hash like this:
Parameters: {"product"=>[{"name"=>"", "price"=>"", "quantity"=>""}], "shop_id"=>"gulshop"}
What can be done for it ?
Your original error 'unknown attribute '0' for Product.' is because the Product class does not have an attribute '0'. I'm not sure where the '0' is coming from as you haven't posted your react code that makes the request.
You can easily make a request from your component using jQuery's .ajax method. e.g
$.ajax({
type: 'POST',
url: '/your_url',
data: {
course: {
name: 'Hello World',
price: 120
}
}
});
You would then have something like the following in your controller..
class ProductController < ApplicationController
def create
#product = Product.create(product_params)
end
private
def product_params
params.require(:product).permit(:name, :price)
end
end

Sencha touch customise rest proxy url

I need to pass addition param to jersey server. But how do I submit my url like ..get/{param1}/{param2}/{param3}
Here is my js file
Ext.define('bluebutton.view.BlueButton.testing', {
extend: 'Ext.form.Panel',
xtype: 'testing',
requires: [
'bluebutton.view.BlueButton.TransactionList',
'bluebutton.view.BlueButton.MemberPopUp',
'bluebutton.view.BlueButton.MemberDetail',
'bluebutton.store.BlueButton.MemberList',
],
config: {
id:'register',
items :[
{
xtype: 'textfield',
name: 'name',
label: 'Name'
},
{
xtype: 'emailfield',
name: 'email',
label: 'Email'
},
{
xtype: 'button',
text: 'Send',
handler: function(button) {
var form = Ext.getCmp('register');
values = form.getValues();
// Select record
//If load data , restful will using "get", url will be /users/1
var User = Ext.ModelMgr.getModel('bluebutton.model.BlueButton.MemberList');
User.load(123,
{
success: function(user) {
alert(user.get('fullName'));
}
}
);
}
}
],
}
});
Model.js
Ext.define('bluebutton.model.BlueButton.MemberList', {
extend: 'Ext.data.Model',
config: {
idProperty: 'memberModel',
fields: [
{ name: 'fullName' },
{ name: 'singer' },
],
proxy: {
type: 'rest',
url: 'http://localhost:8080/RESTFulExample/rest/json/metallica/get',
reader: 'json',
actionMethods: {
create: 'GET',
read: 'POST',
update: 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
},
writer: {
type: 'json',
},
}
}
});
But now I only able to pass my url like ..get/123 Please guide me some solution.Thanks
2 things coming to my mind, First do not write proxy inside model definition, instead set it in initialize function of store where you can look at config data and create url on its basis. e.g.
initialize: function() {
var myId = this.config.uid;
this.setProxy({
type: 'rest',
url: 'http://localhost:8080/RESTFulExample/rest/json/metallica/get/'+myId,
reader: 'json',
actionMethods: {
create: 'GET',
read: 'POST',
update: 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
},
writer: {
type: 'json',
},
});
}
and you can pass id to load when you create the store like this:
var memberStore = Ext.create('bluebutton.store.BlueButton.MemberList', {
uid : 123
});
2nd way could be writing your own proxy extending Ext.data.proxy.Rest and implementing buildUrl such that it checks for data and append it to url. e.g.
buildUrl: function(request) {
var me = this,
url = me.callParent(arguments);
if(!Ext.isEmpty(someData)){
url = Ext.urlAppend(url, "data="+someData);
}
return url;
}
I hope it helps.
EDIT
Sample code for custom proxy which I have used in past to append some token to every request
Ext.define('myapp.proxy.CustomJsonpProxy', {
extend: 'Ext.data.proxy.JsonP',
alias: 'proxy.customjsonpproxy',
buildUrl: function(request) {
var me = this,
url = me.callParent(arguments);
if(!Ext.isEmpty(loggedInUserToken)){
url = Ext.urlAppend(url, "token="+loggedInUserToken);
}
return url;
}
});
the below code worked for me....to set a param to an url
myStore.getProxy().getApi().read = myStore.getProxy().getApi().read + param;

extjs editor grid update rails

i am trying to update records displayed in editor grid..but instead of updating same record, a new record gets inserted into the database...what am i missing??pllzz help..following is my JsonStore code :
Ext.data.Api.restActions = {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE' };
ProdStore = Ext.extend(Ext.data.JsonStore, {
constructor: function(cfg) {
cfg = cfg || {};
ProdStore.superclass.constructor.call(this, Ext.apply({
storeId: 'ProdStore',
id:'ProdStore',
url: 'products.json',
root: 'proddata',
restful:true,
idProperty:'id',
successProperty:'success',
autoLoad:true,
autoSave:false,
batch:true,
writer: new Ext.data.JsonWriter({
encode: false,
listful: false,
writeAllFields: false}),
fields: [
{ name:'customer_id'},{ name: 'prodnm'},
{ name: 'qty'}, { name: 'rate' }, { name: 'amt'}
]
}, cfg));
}
});
new ProdStore();
The idProperty set on the store should be the field that represents unique rows in the database. Perhaps customer_id in this case?
If this does not fix the issue, I would have to see the back end code to see how the save is being handled.

Resources