Rails 3 - Render JS after rendering JSON - ruby-on-rails-3

How do I execute a jquery js after rendering a json page?
respond_to do |format|
format.html
format.json { render :partial => "tables" }
format.js
end
The tables.json.erb gets rendered but the js.erb file does not.

The code in js.erb won't be executed, it's for js response.
You should write the code in the ajax success callback function.
For example:
$.getJSON('your_request_uri', function(data){
// write your code here.
});

Related

Rails 5.1 scaffolded create method returns status 200 on failure

In using the rails 5.1.4 scaffolding for controllers I see that the default approach to deal with a save failure in the #create method is to render #new again (with a status of 200).
respond_to do |format|
if #company.save
format.html { redirect_to #company, notice: 'Company was successfully created.' }
format.json { render :show, status: :created, location: #company }
else
format.html { render :new }
format.json { render json: #company.errors, status: :unprocessable_entity }
end
end
Is there some good reason why the HTML response doesn't render 422 like the JSON version?
The reason this is a problem is that it makes testing the response code difficult in integration tests (i.e. validation error or not the #create method is going to return 200).
Most likely the reason is that historically, most browsers don't tend to understand a lot of the HTTP codes - they only deal with some very simple ones. I think they mostly just discard ones they don't understand.
But there's no reason why you can't change create to send the most appropriate HTTP response-code and start making the web a better place one website at a time :)

How to construct form_tag URL that PUTs to an external API

I'm using the Shopify API http://api.shopify.com/
And the Shopify Gem: https://github.com/Shopify/shopify_api that does most of the heavy lifting- just can't quite figure out how to make it work.
To update an #variant object I need to PUT here: PUT /admin/variants/#{id}.json
In config/routes.rb I made default resource routes with resources :variants and now I'm trying to make a form that updates a variant resource but can't configure the form to have the proper action.
Basically I'm constructing form_tag with a text field input that takes an integer and updates variant.inventory_quantity
Rake Routes give me this:
rake routes:
variants GET /variants(.:format) variants#index
POST /variants(.:format) variants#create
new_variant GET /variants/new(.:format) variants#new
edit_variant GET /variants/:id/edit(.:format) variants#edit
variant GET /variants/:id(.:format) variants#show
PUT /variants/:id(.:format) variants#update
DELETE /variants/:id(.:format) variants#destroy
You need to declare variants resource under admin namespace like this:
config/routes.rb
namespace :admin do
resources :variants
end
EDIT:
You don't have to do anything special for Rails to accept JSON. Rails will convert the JSON you passed in PUT into params and make it available to update method.
Here is the standard implementation of 'update' method:
app/controllers/admin/variants_controller.rb
def update
#variant = Variant.find(params[:id])
respond_to do |format|
if #variant.update_attributes(params[:variant])
format.html { redirect_to(#variant,
:notice => 'Variant was successfully updated.') }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => #variant.errors,
:status => :unprocessable_entity }
end
end
end
Refer to Rails guide and layout and rendering for details.

How to render JSON in Rails view

I've tryed the solution of following example: In Rails, how do you render JSON using a view?
But my problem is that the database already has a JSON string saved, I pull the json string and then I should be able to display the JSON file in the the view.
I'm using this because an android tablet should be able to visit the same url but depending on its settings (send by a POST) a different JSON file should be displayed, the android tablet then fetches the json and use it to configure some options.
So I already have a full working json file, i'm looking for a way to display it in a view (without rendering html tags and other stuff). I tryed the following (yes I've added respond_to :json) :
# def show_json (#config is the record, #config.json_config is the actual json configuration file
#config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
format.json
end
Then my view I have
#show_json.json.erb
<%= #config.config_json %>
Then the HTML I get to see (no errors are given)
<html><head><style type="text/css"></style></head><body></body></html>
Thanks!
EDIT
I'm using rails 3.2.3
Here is my routes (only relevant parts)
match '/events/config', to: "events#show_json", as: :show_json
resources :events do
member do
get :select_item
get :category
end
end
Then also the controller (partial)
respond_to :html, :json, :js
def show_json
#terminal_id = params["mac"]
terminal_id = "3D:3D:3D:3D:3D:3D"
event = current_user.events.where("date(endtime) > ? AND date(starttime) < ?", Time.now.to_s, Time.now.to_s).first
if event.nil?
# Nothing got returned so we use the default event
event = current_user.events.where('"default" = ?', true).first
end
logger.info "MAC: #{terminal_id}"
terminal = current_user.terminals.where(serial: terminal_id).first
logger.info "Terminal: #{terminal.attributes.inspect}"
logger.info "#{event.attributes.inspect}"
#config = event.et_relationships.where(terminal_id: terminal).first
logger.info "CONFIG #{#config[:config_json]}"
respond_to do |format|
format.json { render json: #config[:config_json] }
end
end
Use render:
#config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
format.json { render json: #config }
end
And then you have path /:model/:action.json.

Rails render works in console but does not load page

My goal is to render html from an AJAX call. Changing the dataType to 'html' in my AJAX call seemed to work in that on my console it happily claims that the render was successful:
Rendered admin/articles/show.html.erb within layouts/application (108.1ms)
Completed 200 OK in 185ms (Views: 112.6ms | ActiveRecord: 2.8ms)
but the page does not change.
Here's some code:
View:
<span id='show' class="ui-icon ui-icon-extlink" article_id=<%=article.ID %> onmouseover="this.style.cursor='pointer'"></span>
jquery:
$('#show').live("click",function(evt){
evt.preventDefault();
var article_id=$(this).attr("article_id");
$.ajax({
success : null,
type : 'GET',
url : '/admin/articles/show',
dataType : 'html',
data: {
id: article_id
},
});
});
and my controller:
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html
format.xml { render :xml => #article }
end
end
routes.rb
match 'articles/show' => 'articles#show', :via => :get
I know it's an odd request to want to render html from AJAX but it's the easiest way that I can think to have a clickable link contained in a span tag.
Using Rails 3.0.1, Ruby 1.9.2 and JQuery
usually ajax request ha js type,if you can change type to js these changes will works
controller
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html
format.js
format.xml { render :xml => #article }
end
end
then in app/views/articles/show.js.erb write javascript code to update page content like
$("#yourDiv1").html("blah blah");
$("#yourDiv2").html("whatever");
and following approach will work for both html and JS
$.ajax({
success : null,
type : 'GET',
url : '/admin/articles/show',
dataType : 'html',
data: {
id: article_id
},
}).done(function( html ) {
$("#yourDIv").html(html);
});

not able to load a view when I disable javascript rails 3

Here is my controller code:-
def image_test
respond_to do |format|
format.js {render :layout => false}
format.html {redirect_to image_test_path}
end
end
I have got a partial by the name of _image_test.html.erb and and a simple view image_test.html.erb
In my routes I have done this:-
match "/image_test", :to => "/index#image_test"
It works fine when the javascript is enabled in the borwser however when I disable the javascript I want it to redirect me to my image_test.html.erb file. Instead I get a no route match error.
Please help me with this.
Thanks,
I created a workaround for this solution which is giving the desired result of redirecting to another page if javascript is disabled in a browser but I do not know if this is the rails way.
I created empty action corresponding view for those actions and redirected to those views in case javascript is disabled.
Here is an example of what I did :-
def javascript_enabled_view
respond_to do |format|
format.js {render :layout => false}
format.html {redirect_to :action => "javscript_disabled_view"}
end
end
I have got a corresponding js.erb file and the partial for the above action which will work if javascript is enabled in the browser.
def javascript_disabled_view
end
I have got the corresponding html.erb file which will work in case javascript is disabled in the browser.
Thanks,