i m working with extjs 4 & rails 3.
I want to have validation for uniqueness of field that is on extjs form.
I want to have validation on Rails model for uniqueness, so i have done follwing on my rails model :
validates_uniqueness_of :search_key, :message => "Duplicate value found"
I am inserting new values of form into store as follows :
store.add(values);
If validation fails, the record does not get inserted into database.
Now I want to pop an alert box indicating that the entry is duplicate when validation fails, so that user can edit field.
How can i make this communication betwn rails controller & extjs form for validation?
Also would rails callback will be useful in it?
Here is how to pass messages returned from server to extjs app, I assume you can modify this to suit your need, or let me know if I need to clarify anything:
Extjs
in model, add:
proxy: {
type: 'rest',
url: '/manifest-items',
reader: {
type: 'json', // We expect the server to give us a JSON string as a response
root: 'rows',
totalProperty: 'total',
messageProperty: 'message',
}
},
Rails Controller
Then, in both cases of error or success, returned response should be:
render :json => {:success => false, :message => "some error", :rows => [something], :total => x}.to_json
Back to Extjs
In extjs, the message can be accessed as follows:
important: note the difference between getting error message in failure and success cases.
manifestItem.save({
success: function(records, operation) {
Ext.Msg.alert(operation.resultSet.message);
},
failure: function(records, operation) {
Ext.Msg.alert(operation.error);
}
});
Related
I'm currently trying to make an API doc page thanks to nelmio-api-bundle. I only have one route which is a POST route. I'm receiving a JSON in the body of the request and I'm using the Serializer from symfony to deserialize it in a DTO. I'm also using a DTO for the response (which contains the status code, a bool set to true or false, and a message). Now I'm trying to use these DTO (for input and output) to build the API documentation with nelmio-api-bundle but how to make it ? I'm using PHP8.1 attributes to make it, for response it almost works (except that the response is shows as an array) but I don't know how to make it for the inputs.
Here is my current code:
#[Route('/user', methods: ['POST'])]
#[OA\Parameter(
name: 'user',
description: 'The user information in JSON',
in: 'query',
required: true
)]
#[OA\Response(
response: 200,
description: 'Returns the success response',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: SuccessResponseDTO::class))
)
)]
public function registerUser(Request $request, LoggerInterface $logger): JsonResponse
{
//the code to register the user
}
And here is the result:
Do someone know how to make it ?
I'm pretty new on Nodejs and sails.
I'm implementing a server which is similiar to Twitter. In user model, there should be 2 fields: follower and following, and the 2 fields are association of the model 'user' itself.
My question is when the model have only 1 association, either follower or following, it works.
However, when both follower and following included, there would be en error.
The code is something like this:
module.exports = {
attributes: {
alias: {
type:'string',
required: true,
primaryKey: true
},
pwd: {
type: 'string',
required: true
},
follower: {
collection: 'user',
via: 'alias'
},
following:{
collection: 'user',
via: 'alias'
}
}
The code will cause such error:
usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115
throw new Error('Trying to associate a collection attribute to a model tha
^
Error: Trying to associate a collection attribute to a model that doesn't have a Foreign Key. user is trying to reference a foreign key in user
at References.findReference (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115:11)
at References.addKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:72:22)
For such usage your model definition is incorrect, namely the via keywords. As per the waterline associations docs the via keyword references the other side of the association. So, for a follower the other side is following and vice-versa. In other words:
follower: {
collection: 'user',
via: 'following'
},
following:{
collection: 'user',
via: 'follower'
}
You can check a full working example at: https://github.com/appscot/sails-orientdb/blob/master/test/integration-orientdb/tests/associations/manyToMany.selfReferencing.js
I would like to know how to use rails as backend for my iOS app.
All I need is a User with email and password to authenticate using devise.
I already have a User created with devise and rails 4.
I did find this post http://jessewolgamott.com/blog/2012/01/19/the-one-with-a-json-api-login-using-devise/ explaining what I need, but some things are still missing.
When I try to do a POST via my iOS app, I get the message "Can't verify CSRF token authenticity". How do I solve that without skipping the filter verify_authenticity_token ?
How would the request code for the iOS look like? Right now I'm doing a POST to http://localhost:3000/api/users/sign_in.json and setting the HTTPBody = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&jsonError], but the rails server is receiving only a string as key with the entire json dictionary, not an actual json dictionary.
params = {"{\"user\":{\"email\":\"qwe\",\"password\":\"123\"}}"=>nil, "action"=>"create", "controller"=>"api/sessions", "format"=>"json"}
How would I do an https request instead of http, so I can hide the password and email fields in case someone else tries to watch my internet traffic?
Thank you very much.
To use Rails Applications Mobile and Android and IOS, necessarily you have to use JSONP: example:
JS sample:
$.ajax({
url: '/api_mobile',
jsonp: "callback",
dataType: "jsonp",
cache: true,
data: {method: 'login', other_data ...},
success: function(res) {
// response object
console.log(res)
},
error: function(request, status, error) {
alert("Error server: " + request.status);
}
});
RAILS 4:
protect_from_forgery with: :exception, only: :api_mobile
# route /api_mobile
def api_mobile
json = {error: 'Not found Method'}
case params[:method]
when: 'login'
if User.login(params[:username], params[:password])
json = {notice: 'Login success'}
else
json = {error: 'Error Username or Password'}
end
end
render json: json, :callback => params[:callback]
end
All functions must be personalized and parameterized
The frontend: AngularJS 1.1.5, which has ngResource returning a promise's $then function
The backend: Rails 3.2
The problem: Whenever I call the Card.update action from inside a function in an AngJS controller, I get no response from attempting to log both the success and error responses. The Card $resource behaves as expected works when calling the Card.update action from outside the function.
Rails Associations
Deck has_and_belongs_to_many :cards
Card has_and_belongs_to_many :decks
Rails routes
resources :cards do
get '/decks' => 'cards#decks', on: :member
end
Rails Card Controller 'update' action
def update
#card = Card.where( id: params[:id] ).first
unless params[:deck_id].nil?
#deck = Deck.where( id: params[:deck_id] ).first
#deck.cards << #card
end
render json: Card.update( params[:id], params[:card] )
end
Cards Resource Factory
app.factory "Card", ($resource) ->
$resource "/cards/:id",
id: "#id"
,
index:
method: "GET"
isArray: true
show:
method: "GET"
isArray: false
create:
method: "POST"
update:
method: "PUT"
destroy:
method: "DELETE"
decks:
method: "GET"
isArray: true
url: 'cards/:id/decks'
Cards update function (inside AngJS Controller): (Success/error messages aren't logged to the console).
$scope.updateCard = ( card_id, old_deck, new_deck ) ->
console.log 'CardCtrl updateCard function'
card_id = parseInt(card_id)
old_deck = parseInt(old_deck)
new_deck = parseInt(new_deck)
Card.update( id: card_id, deck_id: new_deck ).$then (success, error) ->
console.log 'Success'
console.log success
console.log 'Error'
console.log error
Introduction
I solved my own problem. I used this Github comment from Misko Hevery as reference.
Why my PUT request wasn't executing:
Apparently, in Angular 1.1.x, if you ever leave the angular execution context, you'll be outside of Angular's $scope.$apply function. In my case, I was working with JQuery UI's sortable function - whenever a Card was placed in a new Deck, I wanted to update the Deck's cards to reflect that update.
To the best of my understanding, because of this, I was outside the angular execution context. ngResource wouldn't execute the PUT statement and the $then function of the Angular's promise object will never be called.
The solution:
Simply wrapping the $scope.$apply function around the Card.updateaction allowed the action to execute, which subsequently allowed the $then function to execute. See the code example below for further clarification:
$scope.$apply ->
Card.update(
id: 1
deck_id: 2
front: "HELLO WORLD!"
).$then ((success) ->
console.log "Success"
console.log success
), (error) ->
console.log "Error"
console.log error
I am building my first Rails 3.1 engines plugin in which i have controller called initiatives_controller and have a action know as upload whenever i try to make a call to upload action via jquery ajax "post" call its returning me 404 error I feel there is some issue in routes.rb because it used work in Rails 3.0
My routes.rb looks like
Marcal::Engine.routes.draw do
resources :media
resources :initiatives
post "initiatives/upload"
end
My initiatives_controller.rb
class InitiativesController < ApplicationController
def upload
puts "hiiiii"
#medium = Medium.new(params[:medium])
if #medium.save
render :json => { 'status' => 'success' }
else
render :json => { 'status' => 'error' }
end
end
end
end
And i used do ajax call as below
$.ajax({
url: "/initiatives/upload",
type: "POST",
data: "medium=something"
dataType: "json",
success: function(sucessdata)
{
alert("success");
}
});
end
Your dummy app is probably mounted on "/marcal" which is the default when you create a mountable engine. You're ajax probably doesn't simple because it sends the POST on "/initiatives/upload" instead of the desired "/marcal/initiatives/upload".
You might want to rename your javascript file from "name.js" to "name.js.erb" and change it's content to:
$.ajax({
url: "<%= root_path %>initiatives/upload",
type: "POST",
data: "medium=something"
dataType: "json",
success: function(sucessdata)
{
alert("success");
}
});
root_path is the key here.