I'm fairly new to API in Rails, and so I will need some assistance for the issue that I am facing.
All I want is to create a record on the database of the API through a POST request from my application.
That is to create a record on both databases (my database and the on the database of the API through a POST request from my application) whenever I create a book.
So this is what I've done so far:
For the app that will consume the API I am using the HTTParty gem.
I have tried to implement in my create action of the Books Controller using the code below:
#result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
:body => { :name => '#{name}',
:author => '#{author}',
:description => '#{description}',
:category_id => '#{category_id}',
:sub_category_id => '#{sub_category_id}'}.to_json,
:headers => { 'Content-Type' => 'application/json', 'Authorization' => '77d22458349303990334xxxxxxxxxx' })
Here is my Books Controller for creating books
require 'httparty'
class BooksController < ApplicationController
include HTTParty
before_action :set_book, only: [:show, :edit, :update, :destroy]
before_action :authenticate_admin!, except: %i[show index]
skip_before_action :verify_authenticity_token
# GET /books
# GET /books.json
def index
#books = Book.search(params[:keywords]).paginate(:page => params[:page], :per_page => 9).order('created_at DESC')
end
# GET /books/1
# GET /books/1.json
def show
end
# GET /books/new
def new
#book = Book.new
end
# GET /books/1/edit
def edit
end
# POST /books
# POST /books.json
def create
#book = Book.new(book_params)
respond_to do |format|
if #book.save
format.html { redirect_to #book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: #book }
else
format.html { render :new }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
end
#result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
:body => { :name => '#{name}',
:author => '#{author}',
:description => '#{description}',
:category_id => '#{category_id}',
:sub_category_id => '#{sub_category_id}'}.to_json,
:headers => { 'Content-Type' => 'application/json', 'Authorization' => '77d22458349303990334xxxxxxxxxx' })
end
# PATCH/PUT /books/1
# PATCH/PUT /books/1.json
def update
respond_to do |format|
if #book.update(book_params)
format.html { redirect_to #book, notice: 'Book was successfully updated.' }
format.json { render :show, status: :ok, location: #book }
else
format.html { render :edit }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
end
end
# DELETE /books/1
# DELETE /books/1.json
def destroy
#book.destroy
respond_to do |format|
format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_book
#book = Book.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def book_params
params.require(:book).permit(:name, :author, :description, :category_id, :sub_category_id)
end
end
But it still doesn't create these books on the database of the API through the post request when I create books.
Please any form of assistance will be highly appreciated.
Thank you.
Check you logs when you do the request, but I suspect you need to change your body to:
{
:book => {
:name => '#{name}',
:author => '#{author}',
:description => '#{description}',
:category_id => '#{category_id}',
:sub_category_id => '#{sub_category_id}'
}
}.to_json
Note that book key at the top is the difference.
Following contributions from #paulo-fidalgo and #tejasbubane, I found a working solution to the issue.
Here is the corrected HTTParty Post Request
#results = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
:body => {
:name => "#{#book.name}",
:author => "#{#book.author}",
:description => "#{#book.description}",
:category_id => "#{#book.category_id}",
:sub_category_id => "#{#book.sub_category_id}"}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => '77d22458349303990334xxxxxxxxxx'
}
)
Related
I am trying to create search form using ransack on rails. I have run into a small problem.
I get an error
param is missing or the value is empty: information
When I submit the search.
Information_controller.rb
class InformationController < ApplicationController
before_action :set_information, only: [:show, :edit, :update, :destroy]
respond_to :html
# Add the breadcrumbs
require 'uri'
# User must authenticate to use all actions in the users controller
before_filter :authenticate_user!, except: [ :home, :show, :splash]
def index
#search = Information.search(params[:q])
#information = params[:distinct].to_i.zero? ?
#search.result :
#search.result(distinct: true)
#information = #information.page(params[:page]).per(10)
respond_with #information
end
def admin
#search = Information.search(params[:q])
#information = #search.result
#search.build_condition
end
#def search
##q = Information.ransack(params[:q])
##information = #q.result(distinct: true)
#end
# GET /information/1
# GET /information/1.json
def show
session[:return_to] = request.fullpath
end
# GET /information/new
def new
#information = Information.new
end
# GET /information/1/edit
def edit
end
# POST /information
# POST /information.json
def create
#information = Information.new(information_params)
respond_to do |format|
if #information.save
format.html { redirect_to #information, notice: 'Entry was successfully created.' }
format.json { render :show, status: :created, location: #information }
else
format.html { render :new }
format.json { render json: #information.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /information/1
# PATCH/PUT /information/1.json
def update
respond_to do |format|
if #information.update(information_params)
format.html { redirect_to #information, notice: 'Entry was successfully updated.' }
format.json { render :show, status: :ok, location: #information }
else
format.html { render :edit }
format.json { render json: #information.errors, status: :unprocessable_entity }
end
end
end
# DELETE /information/1
# DELETE /information/1.json
def destroy
#information.destroy
respond_to do |format|
format.html { redirect_to information_index_url, notice: 'Entry was successfully removed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_information
#information = Information.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def information_params
params.require(:information).permit(:name, :description, :show, :date, :heading, :subheading, :image, :places, :data_type, :reference)
end
end
Search form
<%= search_form_for(
#search,
:url => admin_index_path,
html: { method: :post }
) do |f| %>
<%= f.condition_fields do |c| %>
<%= render "condition_fields", f: c%>
<% end %>
<p><%= link_to_add_fields "Add Conditions", f, :condition %>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
routes
Rails.application.routes.draw do
root :to => 'information#splash'
devise_for :users, :skip => [:sessions], :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
as :user do
get 'signin' => 'devise/sessions#new', :as => :new_user_session
post 'signin' => 'devise/sessions#create', :as => :user_session
delete 'signout' => 'devise/sessions#destroy', :as => :destroy_user_session
end
##########################################
# ADMIN #
##########################################
#admin panel
get '/admin' => 'information#admin'
#get '/admin/new' => 'information'
resources :information, path: '/admin'
get '/home/:id', to: 'information#show'
get 'home' => 'information#index', :as => :home
concern :paginatable do
get '(page/:page)', :action => :index, :on => :collection, :as => ''
end
concern :paginatable do
get '(page/:page)', :action => :information, :on => :collection, :as => ''
end
#get '/new' => 'information#new'
#get '/public' => 'information#'
##########################################################
resources :information
resources :admin
end
Thank you. If you need more details please ask :^)
I'm sending the following JSON to Rails 4.1.0
Started POST "/orders.json" for 127.0.0.1 at 2015-08-11 15:19:34 +0200
Processing by OrdersController#create as JSON
Parameters: {"order"=>{"name"=>"Jon", "surname"=>"Do", "line_items_attributes"=>[{"work_id"=>16, "quantity"=>1, "total_price"=>34.5}, {"work_id"=>12, "quantity"=>2, "total_price"=>40}]}}
Unpermitted parameters: line_items_attributes
but I'm getting Unpermitted parameters error. My Order model:
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :dispatch_method
belongs_to :payment_method
has_many :line_items, :dependent => :destroy
accepts_nested_attributes_for :line_items
end
My orders_controller.rb
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
def index
#orders = Order.all
end
def show
end
def new
#order = Order.new
end
def edit
end
def create
#order = Order.create(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'Order was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to orders_url }
format.json { head :no_content }
end
end
private
def set_order
#order = Order.find(params[:id])
end
def order_params
params.require(:order).permit(:name, :surname, line_items_attributes: [:id, :work_id, :quantity, :total_price])
end
end
I'm able to create and save a new instance of order, but not of a line_item.
You can try to redefine your order_params like this:
def order_params
json_params = ActionController::Parameters.new(JSON.parse(params[:order]))
return json_params.require(:name, :surname).permit(line_items_attributes: [:id, :work_id, :quantity, :total_price])
end
As you see, I am parsing params[:order] to avoid parsing the full params var. You might need to add another json level here but I hope you get the idea.
something like this
render :json => #booking, :include => [:paypal,
:boat_people,
:boat => {:only => :name, :include => {:port => {:only => :name, :include => {:city => {:only => :name, :include => {:country => {:only => :name}}}}},
:boat_model => {:only => :name, :include => {:boat_type => {:only => :name}}}}}]
I'm new in rails and i need a help.
I wanna to do a grouped selection on rails but i dont know how i can do it.
i have 3 db tables cars, car_brands and car_models. When i add new car i need to select car model, how i can do it with gtouped selection.
models/car_brand.rb
class CarBrand < ActiveRecord::Base
has_many :cars
has_many :car_models
mount_uploader :logo, CarBrandImgUploader
end
models/car_model.rb
class CarModel < ActiveRecord::Base
has_many :cars
belongs_to :car_brand
end
cars_controller.rb
class CarsController < ApplicationController
before_action :set_car, only: [:show, :edit, :update, :destroy]
before_action :set_model, only: [:index, :new, :edit]
# GET /cars
# GET /cars.json
def index
#cars = Car.all
end
# GET /cars/1
# GET /cars/1.json
def show
end
# GET /cars/new
def new
#car = Car.new
end
# GET /cars/1/edit
def edit
end
# POST /cars
# POST /cars.json
def create
#car = Car.new(car_params)
respond_to do |format|
if #car.save
if params[:ImagesCars]
params[:ImagesCars]['image'].each do |a|
#ImagesCar = #car.ImagesCars.create!(:image => a, :car_id => #car.id)
end
end
format.html { redirect_to #car, notice: 'Car was successfully created.' }
format.json { render :show, status: :created, location: #car }
else
format.html { render :new }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cars/1
# PATCH/PUT /cars/1.json
def update
respond_to do |format|
if #car.update(car_params)
if params[:ImagesCars]
params[:ImagesCars]['image'].each do |a|
#ImagesCar = #car.ImagesCars.create!(:image => a, :car_id => #car.id)
end
end
format.html { redirect_to #car, notice: 'Car was successfully updated.' }
format.json { render :show, status: :ok, location: #car }
else
format.html { render :edit }
format.json { render json: #car.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cars/1
# DELETE /cars/1.json
def destroy
#car.destroy
respond_to do |format|
format.html { redirect_to cars_url, notice: 'Car was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_car
#car = Car.find(params[:id])
end
def set_model
#models = CarModel.all
#brands = CarBrand.all
end
# Never trust parameters from the scary internet, only allow the white list through.
def car_params
params.require(:car).permit(:title_en, :keys_en, :description_en, :text_en, :title_fr, :keys_fr, :description_fr, :text_fr, :title_ru, :keys_ru, :description_ru, :text_ru, :title_es, :keys_es, :description_es, :text_es, :model_id, :brand_id, :price_day, :price_week, :p_info, :images_cars => [:id, :car_id, :image])
end
end
cars/new.html.haml
= simple_form_for(#car, html: { role: 'form', multipart: true }) do |f|
= f.input :price_day, as: :integer, input_html: {class: 'form-control', placeholder: 'Price Day ej: 150'}
= f.cktext_area :text_en, as: :text, input_html: { class: 'form-control' }, :label => 'EN Website Content Text EN'
=f.input :model_id, collection: #models, as: :grouped_select, group_method: :brand_id
= f.submit 'Save'
i get this error:
undefined method `map' for nil:NilClass
Please help or explain how i can do the grouped selection.
Thx
I have an index action in my controller that I use to render all posts as JSON:
def index
#user = current_user
#posts = Post.all
end
respond_to do |format|
format.html
format.json {
render json: #posts.to_json(:include => {
:user => { :only => [:first_name, :last_name]},
:category => { :only => [:name, :id]}
}),
:callback => params[:callback]
}
end
end
What I'd like to do, is add an additional attribute to each post's JSON output called posted_on, that has a value of: distance_of_time_in_words(post.created_at, Time.now)}
I can't seem to be able to figure out how to approach this. Any help would be appreciated!
Add the method posted_on to Post model
class Post < ActiveRecord::Base
include ActionView::Helpers::DateHelper
def posted_on
distance_of_time_in_words(created_at, Time.now)
end
end
In your controller, pass the methods option to to_json
def index
#user = current_user
#posts = Post.all
end
respond_to do |format|
format.html
format.json {
render json: #posts.to_json(:include => {
:user => { :only => [:first_name, :last_name]},
:category => { :only => [:name, :id]}
}, :methods => :posted_on),
:callback => params[:callback]
}
end
end
I have an issue, I cant figure out what the problem is with the product controller error,
I will not render the product index view page which is what i want to work.
my code is here as follows :
offers controller
class OffersController < ApplicationController
attr_accessible :product , :reserve_price
def your_offer
#your_offer = Offer.new
end
def new
#offer = Offer.new = :your_offer
end
end
and Products Controller
class ProductsController < ApplicationController
before_filter :authenticate, :except => [:index, :show]
# GET /products
# GET /products.xml
def index
#offer = Offer.new
#products = Product.search(params[:search_query])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #products }
end
end
# GET /products/1
# GET /products/1.xml
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #product }
end
end
# GET /products/new
# GET /products/new.xml
def new
#product = Product.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #product }
end
end
# GET /products/1/edit
def edit
#product = Product.find(params[:id])
end
# POST /products
# POST /products.xml
def create
#product = current_user.products.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to(#product, :notice => 'Product was successfully created.') }
format.xml { render :xml => #product, :status => :created, :location => #product }
else
format.html { render :action => "new" }
format.xml { render :xml => #product.errors, :status => :unprocessable_entity }
end
end
end
# PUT /products/1
# PUT /products/1.xml
def update
#product = Product.find(params[:id])
respond_to do |format|
if #product.update_attributes(params[:product])
format.html { redirect_to(#product, :notice => 'Product was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #product.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.xml
def destroy
#product = Product.find(params[:id])
#product.destroy
respond_to do |format|
format.html { redirect_to(products_url) }
format.xml { head :ok }
end
end
end
Offer Model
class Offer < ActiveRecord::Base
belongs_to :product
has_many :reserve_prices
attr_accessible :product, :offer , :reserve_price
validates_presence_of :offer
validate :ensure_meets_reserve_price
private
def ensure_meets_reserve_price
if amount < self.product.reserve_price
errors.add(:amount, "does not meet reserve price")
end
end
private
def reserve_price
product.reserve_price
end
def your_offer
#your_offer = Offer.new
end
def new
#offer = Offer.new = :your_offer
end
end
product index viex snippet
<%= form_for #offer do |f| %>
<%= f.text_field :your_offer %>
<%= f.submit "Make Offer" %>
<% end %>
Could any one see where my eror is ?
Its complaining about #offer = Offer.new
Did you run the migration and restarted the server after creating offers?
Did you declare it as a resource in config/routes.rb as
resources :products, :shallow => true do
resources :offers # or at least just this line
end
Edit:
Get rid of this line and try again
attr_accessible :product, :offer , :reserve_price
is :offer a column in the offers table?
You cannot have columns from another model in attr_accessible.