Rails 3.2.2 - Possible to add custom node to as_json - ruby-on-rails-3

As it's not currently possible for me to use a json templating engine (jbuilder or rabl) as per Rails3 ActionView Template Handlers doesn't work on Production Server I'm wondering how to best change this controller action to include a custom node with as_json (or something else)
class Mobile::AndroidUsersController < SecureMobileUserController
skip_before_filter :authorize, :only => :create
respond_to :json
# POST /mobile_users
# POST /mobile_users.xml
def create
#mobile_user = AndroidUser.find_by_auth(params[:mobile_user][:auth])
unless #mobile_user
#mobile_user = AndroidUser.new(params[:mobile_user])
else
#mobile_user.attributes = params[:mobile_user]
end
respond_to do |format|
if #mobile_user.save
format.json #Add a custom token node here
else
:unprocessable_entity }
format.json { render json: #mobile_user.errors, status: :unprocessable_entity }
:unprocessable_entity }
end
end
end
end
I just need to add a custom node called token that has a value that I get from calling a method on the MobileUser class
:token => MobileUser.next_token

You can change the call to as_json like this:
format.json {render :json => #mobile_user.as_json(:methods => [:next_token])}

Related

Rails: Nested resource and specifying the "nester"

A company has many properties. A property has one company.
In my routes file I got:
resources :companies do
resources :property_managers
end
In the property_manager_controller, my create action looks like this (default scaffold implementation slightly modified to accommodate the company):
def create
#property_manager = PropertyManager.new(params[:property_manager])
#property_manager.company_id = params[:company_id]
respond_to do |format|
if #property_manager.save
format.html { redirect_to company_property_managers_path, notice: 'Property manager was successfully created.' }
format.json { render json: #property_manager, status: :created, location: #property_manager }
else
format.html { render action: "new" }
format.json { render json: #property_manager.errors, status: :unprocessable_entity }
end
end
end
Is there a way in which I do not have to explicitly set the company_id, since it is known within the context of the URL/route?
I guess you could do something like the following, not sure if it's better or not:
class PropertyManagersController < ApplicationController
before_filter :find_company
def new
#property_manager = #company.property_managers.build
end
def create
#property_manager = #company.property_managers.build(params[:property_manager])
respond_to do |format|
...
end
end
private
def find_company
#company ||= Company.find(params[:company_id])
end
end

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.

Rails3 and Rspec2 controller testing with a namespace

I'm trying to test a controller with a name space, following is my controller (/admin/sites_controller.rb):
class Admin::SitesController < AdminController
def create
#site = Site.new(params[:site])
respond_to do |format|
if #site.save
format.html { redirect_to(#site, :notice => 'Site was successfully created.') }
format.xml { render :xml => #site, :status => :created, :location => #site }
else
format.html { render :action => "new" }
format.xml { render :xml => #site.errors, :status => :unprocessable_entity }
end
end
end
end
and following is my routes.rb file
namespace :admin do
resources :sites
end
I'm using rspec2 to test my controller and following is my controller spec
describe Admin::SitesController do
describe "POST create" do
describe "with valid params" do
it "creates a new Site" do
expect {
post :create, :site => valid_attributes
}.to change(Site, :count).by(1)
end
end
end
end
But when I run the spec it gives me the following routing error
Admin::SitesController POST create with valid params creates a new Site
Failure/Error: post :create, :site => valid_attributes
NoMethodError:
undefined method `site_url' for #<Admin::SitesController:0xb5fbe6d0>
# ./app/controllers/admin/sites_controller.rb:47:in `create'
# ./app/controllers/admin/sites_controller.rb:45:in `create'
# ./spec/controllers/admin/sites_controller_spec.rb:78
# ./spec/controllers/admin/sites_controller_spec.rb:77
I guess its because of the 'admin' name space I'm using, but how can I fix that?
I'm using
Rails3
Rspec2
Linux
When you namespace the route, you're creating URL and path helpers that look like this:
HTTP Verb Path action helper
GET /admin/sites index admin_sites_path
GET /admin/sites/new new new_admin_site_path
POST /admin/sites create admin_sites_path
GET /admin/sites/:id show admin_site_path(:id)
GET /admin/sites/:id/edit edit edit_admin_site_path(:id)
PUT /admin/sites/:id update admin_site_path(:id)
DELETE /admin/sites/:id destroy admin_site_path(:id)
So you can either use those directly in your code (i.e. redirect_to admin_site_path(#site) ), or you can do something like:
redirect_to([:admin, #site])

Rails 3.1 respond_to :html with :except

I have the following in my controller:
respond_to :html, :except => :some_action
respond_to :json, :xml
If you hit the :some_action route in a browser (tested with Chrome), you get a 406 Not Acceptable response back. Is there a way to "catch" this in Rails and do something else (like a redirect)?
Additionally, I'm trying to avoid using the block form of respond_to. I'm just curious if there is some way to handle this case.
Check this out: http://ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with
There's a bit about action overriding:
class UsersController < ApplicationController::Base
respond_to :html, :xml, :json
# Override html format since we want to redirect to a different page,
# not just serve back the new resource
def create
#user = User.create(params[:user])
respond_with(#user) do |format|
format.html { redirect_to users_path }
end
end
end

Unexpected dot from helper method

I have the following routings
PosTracker::Application.routes.draw do
get "home/index"
resources :pos
resources :apis
match 'update_data' => 'home#update', :as => :update, :via => :get
root :to => "home#index"
end
Now, when using the link_to helper method:
link_to "text", pos_path(starbase)
I get the following route /pos.13 instead of /pos/13. Obviously, this won't produce valid output. How can I fix this?
Edit: Relevant controller:
class PosController < ApplicationController
# GET /pos
# GET /pos.xml
def index
#do stuff
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #pos }
end
end
# GET /pos/1
# GET /pos/1.xml
def show
#pos = Pos.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #pos }
end
end
end
It seems to me like Rails is recognizing pos_path as your #index action url helper. Generally it will take the symbol you pass to resources and singularize it for a #show action.
The url helper you want to use would be
link_to "text", po_path(starbase)
You can generally find the name of the helper methods by running
rake routes
Or to get the helper for a specific controller
rake routes CONTROLLER=pos