I am using Ruby on Rails 3 and I am trying to retrieve error data from a web service application after making to that an HTTP POST request. I would like to receive that data including the errors root.
In a service app controller I have
format.json {
render :json => #account.errors, :status => 202
}
The return data returned, for example, is
{\"base\":\"Invalid submitting\",\"name\":\"To short\"}
I would like to receive back data like this
# Note 'errors'
"{\"errors\":{\"base\":\"Invalid submitting\",\"name\":\"To short\"}"}
How can I make that?
A solution is to make this
render :json => '{"errors":' + #account.errors.to_json + '}'
but I don't think it is the right\correct way. RoR certainly has some features to do that better...
You should be able to construct an equivalent hash and then use that:
error_hash = { 'errors' => #account.errors.to_h }
render(:json => error_hash, :status => 302)
Related
Would it be a good idea to add an standard internal 404 page (not in public but in app/view/shared/ folder). A page where user can move to other existing pages via menu / links etc.
Many good websites allow user to browse their site menu on 404. i.e. If in you login into facebook and click some 404 facebook page. YOu will see feeds chats with 404.
Well, In rails I don't know How to do this. well, I google-ed on it.
and What I found (Should be done to handle 404):
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
What I currently have :
render :text => 'User not found', :status => 404`
What I want to do : (if its not bad solution of handling 404):
render :file => '/view/shared/404.html.erb', :status => 404
Please suggest!
Try rendering like:
render "shared/404", :status => 404
I haven't tried it but from what's said in Two controllers for one shared view in Ruby on Rails answer, this might work.
I'm new to Ruby and Rails. I just completed a course in Laravel, so I am aware of the MVC system(not a newbie as far as the basic concepts are concerned).
I have a rather simple question,
I am sending a POST request to my RAILS REST API,the body of the post request contains a json encoded string like this--->
Array ( [method] => POST [timeout] => 45 [redirection] => 5 [httpversion] => 1.0 [blocking] => 1 [headers] => Array ( ) [body] => {"post_content":"here is the post","post_title":"here we are ","post_author":"1"} [cookies] => Array ( ) )
As you can see,its coming from my php based blog.
My rails API is supposed to be taking the post content and automatically adding links to certains words, by comparing the words with some stuff that i have in an SQLite database.
Ok, so my problem is this:
I just want the response from the Rails controller, I dont want anything loaded into a view. The Rails Controller - returns the content, with 'a href' tags around words that are found in my database. This is to be sent back as the response to my post request, and i want to access it directly as the body of the response.
As of now I dont know how this is to be done. Laravel has the ability to 'return' whatever you want to , at the end of the Controller Action, but in Rails, everything seems to want to load into a view.
I have researched some questions here and found one which said 'render :nothing => true',but that renders nothing at all.Here is what my code looks like.
def process
content = params['post_content']
##perform db function and get back the content with the links embedded.
##HOW TO RETURN THIS CONTENT.
end
Personally, I think, i have to use the render_to_string method, but I have no idea how to do this.
Any help is appreciated.
Best Regards,
Richard Madson.
Some options to consider:
Render just the raw string as the http response body:
render :text => content
Render a view without the default surrounding layout:
render :layout => false
In that case your view could just be:
<%= #content %>
Or render the content as json:
render :json => { :content => content }
The question is, what do you want returned? Text? XML? JSON?
I'm going to assume you want JSON back based on the JSON going in.
respond_to do |format|
format.json { render json: #someobject }
end
It might be helpful to see the rest of the controller method.
If I understand correctly believe what you are looking for is
render :text => "response"
there is also - JSON, XML, nothing, js, file, etc - more information here http://guides.rubyonrails.org/layouts_and_rendering.html
def list
#rings = Ring.order("RAND()")
#JSON RENDERING
render :json => #rings.to_json(:include => [:variations, :stones]), :callback => params[:callback]
end
def show
#showring = Ring.includes(:stones, :variations).find(params[:id])
#other_rings = Ring.select([:id, :stone_count]).where(:style_number => #showring.style_number).reject{ |ring| ring == #showring}
#JSON RENDERING
render :json => {#showring.to_json(:include =>[:variations, :stones]), :other_rings => #other_rings}, :callback => params[:callback]
end
My list view rendering works fine, but when i want to do a show view, with two objects, and showring with includes won't render proper JSON. It is quoting everything in the object with the includes...
JSON output looks like this:
showring => "{"available":"yes","eng...9","stone_y":"149.4"}]}"
other_rings => properly rendered object
On a seperate note, if i have already added the includes to #rings object, why do i then again have to add the association in the "to_json" method?
When you do
render :json => {:show_ring => #showring.to_json(:include =>[:variations, :stones]), :other_rings => #other_rings}
Rails is converting #showring to json (ie getting back a string representation), i.e. the value is the string literal. Instead do
render :json => {:show_ring => #showring.as_json(:include =>[:variations, :stones]), :other_rings => #other_rings}
as_json does all the work of turning the object into a hash but without the final step of turning into a string
if you are going to invest more time in building more JSON objects, you should look into a gem called rabl. It makes building JSON very simple, good for customization which then is good for building API.
I'm having trouble calling a model's show path from within a create controller.
I'm using the Koala gem in a Rails 3.2 app. I'm trying to publish to Facebook's open graph automatically when a User creates a particular record type.
I have a page set up with all the required FB meta tags.
I can run the Koala methods from the console and everything works fine.
But if I try to run this from the controller I get an error.
My controller looks like this:
def create
#fb_model = current_user.fb_models.build(params[:fb_model])
if #fb_model.save
Koala::Facebook::API.new(app_token).put_connections( current_user.fb_uid, "namespace:action", :object => fb_model_url(#fb_model) )
respond_to do |format|
format.html { redirect_to(#fb_model, :notice => 'Successfully created.') }
format.xml { render :xml => #fb_model, :status => :created, :location => #fb_model }
end
else
respond_to do |format|
format.html { render :action => "new" }
format.xml { render :xml => #fb_model.errors, :status => :unprocessable_entity }
end
end
end
When I create a record, my logs show:
Koala::Facebook::APIError (HTTP 500: Response body: {"error":{"type":"Exception","message":"Could not retrieve data from URL."}}):
If I edit the controller to use a static url for testing, everything works fine.
...
if #fb_model.save
Koala::Facebook::API.new(app_token).put_connections( current_user.fb_uid, "namespace:action", :object => "http://myapp.com/fb_model/2" )
...
Why can't I pass the record's url to FB from within the create controller using fb_model_url(#fb_model)?
I eventually got to the bottom of this. It's actually a really frustrating issue, as there is no indication that this is the problem in any logs or elsewhere.
The problem was that I was deploying/ testing on Heroku, and only had 1 web dyno running. My app was unable to handle both the Facebook request and the post/ get simultaneously, causing the error.
This has been addressed in another question Facebook Open Graph from Rails Heroku. It's really not what I was expecting, and I didn't come across this question in any of my earlier searching. Hopefully this can help someone else.
I solved the issue by switching from thin to unicorn.
build is finalised when the parent model is saved, and you dont seem to be operating on a parent.
I think you actually want this:
#fb_model = current_user.fb_models.new(params[:fb_model])
Also you seem to be calling #fb_model.save twice which is wrong.
Thanks for posting your findings - I've been dealing with this issue for the past couple of days and wouldnt have figured that. So when you simply increased your dyno load, you no longer had this error? I was on the verge of just using the Javascript SDK even though my 'put_connections' callbacks work in the heroku console.
I'm looking to have a model that gets created / updated via AJAX. How do you do this in Ruby on Rails?
Also, more specifically: how do you output JSON in RoR?
def create
response = {:success => false}
#source = Source.new(params[:source])
if #source.save
response.success = true
end
render :json => response.to_json
end
All you need to do is call render :json with an object, like so:
render :json => my_object
For most objects, this will just work. If it's an ActiveRecord object, make sure to look at as_json to see how that works. For your case illustrated above, your hash will be transformed to json and returned.
However, you do have an error: you cant access the success key via response.success -- you should instead do response[:success]
jimothy's solution is really good butI believe it isn't scalable in the long term. Rails is meant to be a model, view, and controller framework. Right now JSON is cheated out of a view in default rails. However there's a great project called RABL which allows JSON view. I've written up some arguments for why I think it's a good option and how to get up and running with it quickly. See if this is useful for you: http://blog.dcxn.com/2011/06/22/rails-json-templates-through-rabl/
#source = Source.new(params[:source])
respond_to do | f |
f.html {
# do stuff to populate your html view
# maybe nothing at all because #source is set
}
f.any(:xml, :json) {
render request.format.to_sym => #source
}
end