Record is not updating in rails - ruby-on-rails-3

This is my first rails application. My task is to display, delete and update the records using .ajax(). I have displayed and deleted the records but i cant update the records i couldn't figure out what is going wrong. My controller code is
def update
#aj = Aj.find params[:id]
respond_to do |format|
if #aj.update(aj_params)
format.html { redirect_to #aj, notice: 'Aj was successfully updated.' }
format.json { render :show, status: :ok }
else
format.html { render :edit }
format.json { render json: #aj.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_aj
#aj = Aj.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def aj_params
params.require(:aj).permit(:name, :title, :content)
end
end
and my route file is
match '/ajs/' => 'ajs#update', :via => :patch
match '/ajs/:id/edit' => 'ajs#edit', :via => :get
and could able to edit my form after changing the data when i click on update button it given the error
Couldn't find Aj without an ID
# Use callbacks to share common setup or constraints between actions.
def set_aj
#aj = Aj.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
edited:
I have javascript code in html itself
$(document).on("click", ".edit", function(){
var id = $(this).data('id');
alert("edit"+id)
$.ajax({
url: "ajs/"+id+"/edit",
type: "get",
data: id,
//dataType: "html",
success: function(data) {
$("#mybox").html(data);
$(document).on("click", "#subid", function(){
alert(id);
$.ajax({
url: "ajs/"+id,
type: "patch",
success: function(data) {
alert("success");
},
error: function(){
alert("error")
}
}); // show ajax() closed
});//show click() closed
},
error: function(){
alert("error")
}
}); // show ajax() closed
});//show click() closed
I have added a id for the update button and id name is "subid " when i click on that button i am passing my id am getting id of the row. when i used ajax for passing that id now i am getting another error:
No route matches [PATCH] "/ajs"
Rails.root: /home/liplw015/Documents/rails/ajaxjs
In my console:
Started PATCH "/ajs/134" for 127.0.0.1 at 2014-07-14 09:38:09 +0530
Processing by AjsController#update as */*
Parameters: {"id"=>"134"}
Aj Load (0.4ms) SELECT "ajs".* FROM "ajs" WHERE "ajs"."id" = ? LIMIT 1 [["id", 134]]
Completed 400 Bad Request in 4ms
ActionController::ParameterMissing (param is missing or the value is empty: aj):
app/controllers/ajs_controller.rb:98:in `aj_params'
app/controllers/ajs_controller.rb:69:in `block in update'
app/controllers/ajs_controller.rb:68:in `update'
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack- 4.1.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.9ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.3ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.9ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb (22.5ms)
Started PATCH "/ajs" for 127.0.0.1 at 2014-07-14 09:38:10 +0530
ActionController::RoutingError (No route matches [PATCH] "/ajs"):
actionpack (4.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'

your route is wrong, include id in route
match '/ajs/:id' => 'ajs#update', :via => :patch

Related

rails 3.1 mountable engines HTTP 404 Error on ajax post call

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.

No request params in constraint when testing route

When I run this in practice it works, but I can't seem to write a working test for my route constraint with rspec.
When the test runs the constraint is triggered, but the request params are empty, thus it does not validate and the test fails.
I am running Rails 3.0.9, rspec-rails 2.6.1 and rspec 2.6.0.
config/routes.rb
match ":param1-unique-:param2" => "controller#index",
:constraints => ParamConstraint.new
lib/param_constraint.rb
class ParamConstraint
def matches?(request)
#request ||= request
valid_param1? && valid_param2?
end
def valid_param1?
#request.params[:param1] == "lorem"
end
def valid_param2?
#request.params[:param2] == "ipsum"
end
end
spec/routing/param_constraint_spec.rb
require 'spec_helper'
describe "param constraint routing" do
it "recognizes route for param1 and param2" do
{ :get => "/lorem-unique-ipsum" }.
should route_to(
:controller => "controller",
:action => "index",
:param1 => "lorem",
:param2 => "ipsum"
)
end
end
Update
If I inspect the request in the constraint I get the following output:
#<ActionDispatch::Request:0x007fee140ff910 #env={
"rack.version"=>[1, 1],
"rack.input"=>#<StringIO:0x007fee1446da48>,
"rack.errors"=>#<StringIO:0x007fee1446e768>,
"rack.multithread"=>true,
"rack.multiprocess"=>true,
"rack.run_once"=>false,
"REQUEST_METHOD"=>"GET",
"SERVER_NAME"=>"example.org",
"SERVER_PORT"=>"80",
"QUERY_STRING"=>"",
"PATH_INFO"=>"/lorem-unique-ipsum",
"rack.url_scheme"=>"http",
"HTTPS"=>"off",
"SCRIPT_NAME"=>"",
"CONTENT_LENGTH"=>"0"
}>
I ran into this same issue today, searching for an answer brought me to this page's question. For what it's worth, I had to resort to writing a request spec instead.
context "passing params that satisfy ParamConstraint" do
before do
visit "/lorem-unique-ipsum"
end
it "should serve up a page with content" do
# replace this with some assertion that gets satisfied by
# pages served up when ParamConstraint.new.matches? returns true
page.should have_selector("html body div#foo")
page.should_not have_selector("html body div#bar")
end
end
context "passing params that DO NOT satisfy ParamConstraint" do
before do
visit "/other-unique-other"
end
it "should serve up a page with different content" do
# replace this with some assertion that gets satisfied by
# pages served up when ParamConstraint.new.matches? returns false
page.should_not have_selector("html body div#foo")
page.should have_selector("html body div#bar")
end
end
This doesn't answer your question, which I take to be "how to test routing constraint", as the proper way would be via a routing spec. But given this gap in how request.params works when you use "should route_to", this is a workaround. A request spec, as opposed to a routing spec, will fill request.params correctly.
Same issue exists years later, with rspec-core 3.4.4, rspec-rails 3.4.2, rails 4.2.6. Don't have time to dig into exactly why...
You can use a request spec as suggested above, but don't use it to test the page contents. Instead, replicate a routing test (route_to) by checking the conversion of URL paths to request params:
RSpec.describe 'routes', type: :request do
describe '/:slug' do
it 'routes correctly' do
get '/test-product-slug'
expect(request.params).to eq(
'controller' => 'product',
'action' => :index,
'slug' => 'test-product-slug'
)
end
end
end

extjs4 rails 3 model validation for uniqueness

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);
}
});

Rails 3 ajax response is not executed

I am creating a simple ajax feature into my application where a user can increase a "like count" through a link.
I have managed to get the link to run my controller code and the browser is getting a response back, but the response is not executed.
The like link is in partial:
.likes
.like_up
= link_to( image_tag('/images/thumb_up.png'), '/like/' + question.id.to_s, :remote => true)
#like_count
= 22# question.likecount
.like_down
= link_to( image_tag('/images/thumb_down.png'), '/dislike/' + question.id.to_s, :remote => true)
And it goes into likes_controller:
def up
#like = current_user.likes.create( :question_id => params[:question_id], :like => true )
respond_to do |format|
format.js
end
end
Then in my up.js.haml I simply have a debug javascript:
alert('2');
and nothing else.
When I press the like link in browser the rails log tels me that it has rendered the js.haml
...
Rendered likes/up.js.haml within layouts/application (104.9ms)
Completed 200 OK in 923ms (Views: 116.3ms | ActiveRecord: 20.1ms)
And when I look at the response the browser gets it certainly looks like the up.js.haml rendered into my application layout where the yield tag is placed.
<div class='content'>
alert('2');
</div>
I suspect that this is not what the browser wants to get back. Also when looking at the firebug console during the ajax request, nothing happens after the request is sent.
Could someone find out why this is not working? Every tutorial and guide I have found does this the same way I'm doing here.
First, make sure the content-type is correct:
curl --head -X POST http://localhost:8080/....
I believe the Content-Type should be text/javascript
Second, I think you want to disable the layout so that the DIV doesn't appear in the output.
def up
#like = current_user.likes.create( :question_id => params[:question_id], :like => true )
respond_to do |format|
format.js { render :partial => 'up', :layout => false }
end
end
Or maybe disable it in the whole controller with
layout false
It happened to me in a simple remote form.
Worked after restarting the server even it was the development environment.
Hope I save someone the hour I wasted.
Best regards.

Why do I get a connection timeout for facebook api-video?

This is the API call Im attempting:
http://developers.facebook.com/docs/reference/rest/video.upload
(Video upload is not available in the new Graph API.)
I have tried many variations on the parameters. The code below is my best guess. If I modify the params to be obviously incorrect, change to http (not https) or try to use api.facebook.com for video, I get proper errors back.
However, my code below just waits a few minutes before reporting:
ETIMEDOUT: Connection timed out
Also included is working code to upload a photo - which is almost identical.
Ruby:
# Facebook Old-API method - testing only - this works.
def post_photo
url = "https://api.facebook.com/method/photos.upload"
body = {
nil => File.new(self.media.media_files.first.source_file, 'rb'),
:access_token => self.session.auth_data[:access_token],
:callback => "none",
:aid => "Test Photos",
:caption => "Test",
:uid => self.session.auth_data[:uid],
}
response = RestClient.post url, body
end
# Facebook Old-API method - doesn't work - connection timeout.
def post_video
url = "https://api-video.facebook.com/method/video.upload"
body = {
:nil => File.new(self.media.media_files.first.source_file, 'rb'),
:access_token => self.session.auth_data[:access_token],
:callback => "none",
:title => "Test title",
:description => "Test description",
:privacy => "{ value: 'EVERYONE' }",
:uid => self.session.auth_data[:uid],
}
response = RestClient.post url, body
end
PS: Im in Australia - is the API limited to eg the USA?
Thanks