Angularjs: post data to rails server by service - ruby-on-rails

I want send data from angularjs to rails server. For this, I have an angularjs service that I use GET,POST,DELETE,UPDATE method. I can use GET method, but for other method I cannot use, beacause I have to sent parameter to server, but I cannot do this.
record.js:
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records', function($scope, Session, Records){
$scope.records = Records.index();
}]);
recordService.js:
'use strict';
var app = angular.module('recordService', ['ngResource']);
//angular.module('recordService', ['ngResource'])
app.factory('Records', function($resource) {
return $resource('/api/record.json', {}, {
index: { method: 'GET', isArray: true},
create: { method: 'POST' }
});
})
.factory('Secure', function($resource){
return $resource('/api/record/:record_id.json', {}, {
show: { method: 'GET' },
update: { method: 'PUT' },
destroy: { method: 'DELETE' }
});
});
and I get data in rails server by below code:
class Api::V1::RecordController < Api::V1::BaseController
def index
respond_with(Record.all)
end
def show
#data = Record.find(params[:id]).to_json()
respond_with(#data)
end
def update
#data = Record.find(params[:id])
respond_to do |format|
if #data.update_attributes(record_params)
format.json { head :no_content }
else
format.json { render json: #data.errors, status: :unprocessable_entity }
end
end
end
def create
#data = Record.create(record_params)
#data.save
respond_with(#data)
end
def destroy
#data = Record.find(params[:id])
#data.destroy
respond_to do |format|
format.json { head :ok }
end
end
private
def record_params
params.require(:record).permit(:name)
end
end
I don't know how can I send method from angularjs controller to rails server. I try below code, but I don't successful:
Records.create(function() {
//"name" is the name of record column.
return {name: test3};
});
but I get below error in rails server:
Started POST "/api/record.json" for 127.0.0.1 at 2014-08-30 17:55:27 +0430
Processing by Api::V1::RecordController#create as JSON
How can I fix this problem? How can I send parameter to rails server?
I want send delete method to rails server. I know I have to send record.id to server, I use below type:
//type 1
var maskhare = { record_id: 4};
Secure.destroy(function(){
return maskhare.json;
});
//type 2
Secure.destroy(4);
but I get below error in server:
Started DELETE "/api/record" for 127.0.0.1 at 2014-08-30 19:01:21 +0430
ActionController::RoutingError (No route matches [DELETE] "/api/record"):
I fix correct url in recordService.js, but I don't know why request is send to before url again. Where is the problem?

It looks like you are successfully making a request, the last line there says that a POST request was made and went to the right controller and action.
The problem is strong parameters. You need to add name to the filtered parameters list.
private
def record_params
params.require(:record).permit(:secure, :name)
end
Also rails expects the parameters in the following format: { record: {name: 'something"} }
To fix your second problem
I would try to follow this recipe
Replace your code with this:
app.factory("Secure", function($resource) {
return $resource("/api/record/:id", { id: "#id" },
{
'show': { method: 'GET', isArray: false },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
}
);
});
and then
Secure.destroy({id: 4});
Keep in mind that if you add respond_to :json in your controller then you can omit the .json in the URLs. Like so:
class Api::V1::RecordController < Api::V1::BaseController
respond_to :json
...
end

Related

Rails Ajax Call : Pass JSON to separate controller method

Hey everyone I am having an issue setting up my app. It uses the shopify API and essentially what it does is grab some data via a view and sends it to the controller but I am having issues passing it to another method in the controller to use the API to save the data.
Here is my code :
Controller
class BuilderController < ShopifyApp::AuthenticatedController
def index
urlval = request.fullpath
#urlCheck = urlval.split('/').last
end
def show
url = request.fullpath
#urlID = url.split('/').last
#customers = ShopifyAPI::Customer.search(query: "id:"+ #urlID)
#need to get a way to retrieve the ajax call info here to pass into the update
end
def updateCustomer(notes)
#customers.each do |cus|
cus.note = notes
cus.save()
end
end
def new
notes = params[:notes]
updateCustomer(notes)
render json: notes
end
end
View
<button id="test">TEST</button>
<script>
var butt = document.getElementById('test');
butt.addEventListener("click",function(){
$.ajax({
url: "/builder/new",
type: "GET",
data: {
"notes": [
"test",
"test2"
]
},
success: function(data,text,xhr) {
console.log(text);
console.log(xhr);
console.log(data);
alert('successfully');
},
error: function(data,error){
console.log(data);
console.log(error);
alert("help");
}
});
});
</script>
Rather than a fully separate method, have you looked into the
respond_to method? http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to
You could do (assuming html is the primary request type, change if it isn't):
def index
respond_to do |format|
format.html { actions }
format.json { actions }
end
end
This the method we use to accommodate different request types within the same action. Please let me know if I've misinterpreted your question.
you can use this
update_all(updates) public
Updates all records with details given if
they match a set of conditions supplied, limits and order can also be
supplied. This method constructs a single SQL UPDATE statement and
sends it straight to the database. It does not instantiate the
involved models and it does not trigger Active Record callbacks or
validations.
http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all
def new
notes = params[:notes]
#customer.update_all({note: notes})
respond_to do |format|
format.html {}
format.json { json: #customer.json }
end
end

Show Associated Model Data with React Rails

I'm using the react-rails gem and have two models: Message and User. User has_many :messages.
In my message.js.jsx, I'd like to show the User of that message. In regular erb, it'd just be <%= message.user.name %>. How would I do this in the message.js.jsx component?
You could rename your component to message.js.jsx.erb and use ERB in it, but it will only be compiled once when Rails starts up.
A more React-ish way to handle is to AJAX load the user data in componentDidMount (or a Store, if using Flux).
message.js.jsx
getInitialState: function() {
return { user: { name: '' } };
},
componentDidMount: function() {
$.getJSON('/users/'+ this.props.id +'.json', function(userData) {
if (this.isMounted()) {
this.setState({ user: userData })
}
});
},
You can create a Rails endpoint to return userData as JSON something like this:
users_controller.rb
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # default html response
format.json { render json: #user.to_json(only: [:id, :name]) }
end
end
See Facebook's page on this for more details
I agree with Unixmonkey that is the react way. You can also do it a few more ways.
#user = JSON.parse user.to_json(include: [:messages], only: [:id, :name])
As well as using componentDidMount to hit a JSON endpoint using jbuilder which you can put a timeout on if you want to update dynamically.
componentDidMount: function() {
$.getJSON('/users/'+ this.props.id +'.json', function(user) {
if (this.isMounted()) {
this.setState({ user: user })
}
});
},
Your show.json.jbuilder under user views would look something like this:
json.id #user.id
json.name #user.name
json.messages #user.messages do |message|
json.id message.id
json.content message.content
json.created_at message.created_at
end

Ruby on rails Ajax call showing 404 error

I am making and ajax call to hit the controller but it is showing the 404 error:
My controller method is like:
def get_user_time
if(params[:user])
#user_time_checks = UserTimeCheck.where(:user_id => params[:user])
end
end
And my route for this is like:
post "user_time_checks/get_user_time"
And my ajax script is like:
function get_user_time(id) {
var user_id = id;
if(user_id != ''){
$.ajax({
url:"get_user_time?user="+user_id,
type:"POST",
success: function(time){
console.log(time);
},error: function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
}
});
}
}
Try this:
$.ajax({
url:"user_time_checks/get_user_time",
type:"POST",
data: {
user: user_id
},
success: function(time){
console.log(time);
},error: function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
}
});
Also make sure you really need to do POST method and that rails route does not require specific paramater like :user_id. Basically check the output from
rake routes | grep get_user_time
Your route should be:
post "user_time_checks/get_user_time" => "user_time_checks#get_user_time"
Also, since the purpose of the request is to get some data, you should make it a GET request instead. So:
function get_user_time(id) {
var user_id = id;
if(user_id != ''){
$.get("get_user_time",
{user: user_id})
.success(function(time) {
console.log(time);
})
.error(function(xhr,response){
console.log("Error code is "+xhr.status+" and the error is "+response);
});
}
}
Lastly, maybe you should tell the controller to be able to repond_to json:
def get_user_time
if(params[:user])
#user_time_checks = UserTimeCheck.where(:user_id => params[:user])
respond_to do |format|
format.html # The .html response
format.json { render :json => #user_time_checks }
end
end
end

Render json objects with Angular $resource Rails API

I'm writing my own API controllers using Angular $resource. Is it better to render all objects on the RAILS side controller with 1 resource, or make 3 different resource calls.
app.factory("responseResource", function($resource) {
return $resource("/api/v1/responses/:id", {id: "#id" },
{
get: { method: "GET" },
update: { method: "PUT" }
});
});
class Api::V1::ResponsesController < Api::V1::ApiController
def show
#response = Response.find(params[:id])
#rubric = Rubric.find(#response.rubric_id)
#questions = #rubric.questions
render json: { response: #response, questions: #questions, rubric: #rubric }
end
end

How to pass json response back to client

In my ruby on rails code I want to send back json response to client. Since I am new to ruby on rails I do not know how can I do this. I want to send error = 1 and success = 0 as json data if data does not save to database and if it successfully saves that it should send success = 1 and error = 0 Please see my code below
here is my controller
class ContactsController < ApplicationController
respond_to :json, :html
def contacts
error = 0
success = 1
#contacts = Contact.new(params[:contact])
if #contacts.save
respond_to do |format|
format.json { render :json => #result.to_json }
end
else
render "new"
end
end
end
here is my javascript code
$('.signupbutton').click(function(e) {
e.preventDefault();
var data = $('#updatesBig').serialize();
var url = 'contacts';
console.log(data);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
There are tons of other elegant ways, but this is right:
class ContactsController < ApplicationController
def contacts
#contacts = Contact.new(params[:contact])
if #contacts.save
render :json => { :error => 0, :success => 1 }
else
render :json => { :error => 1, :success => 0 }
end
end
end
Add also a route to routes.rb. If you need to use html response you have to include respond_to do |format|.
You have to adjust your routes to accept json data
match 'yoururl' => "contacts#contacts", :format => :json
Then it will work

Resources