I am having trouble posting to a JSON field (using postman) in my Ruby + Rails web app. I am confused as to what the controller permissions (strong params) need to be and the subsequent posting format.
I am trying to send in raw format using postman (Content-type is set to application/json)
{"recipe":{"recipe_id":"174a4839020d0820","Category":"Eaten"}, "Nuts":{...}, "Milk":{...}}
My controller looks like:
class OnboardingsController < ApplicationController
before_action :set_onboarding, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :if => Proc.new { |c| c.request.format == 'application/json' }
# GET /onboardings
# GET /onboardings.json
def index
#onboardings = Onboarding.all
end
# GET /onboardings/1
# GET /onboardings/1.json
def show
end
# GET /onboardings/new
def new
#onboarding = Onboarding.new
end
# GET /onboardings/1/edit
def edit
end
# POST /onboardings
# POST /onboardings.json
def create
ap params
#onboarding = Onboarding.new(onboarding_params)
respond_to do |format|
if #onboarding.save
format.html { render :json => #onboarding.to_json , notice: 'Onboarding was successfully created.' }
format.json { render :show, status: :created, location: #onboarding }
else
format.html { render :new }
format.json { render json: #onboarding.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /onboardings/1
# PATCH/PUT /onboardings/1.json
def update
respond_to do |format|
if #onboarding.update(onboarding_params)
format.html { redirect_to #onboarding, notice: 'Onboarding was successfully updated.' }
format.json { render :show, status: :ok, location: #onboarding }
else
format.html { render :edit }
format.json { render json: #onboarding.errors, status: :unprocessable_entity }
end
end
end
# DELETE /onboardings/1
# DELETE /onboardings/1.json
def destroy
#onboarding.destroy
respond_to do |format|
format.html { redirect_to onboardings_url, notice: 'Onboarding was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_onboarding
#onboarding = Onboarding.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def onboarding_params
params.require(:onboarding).permit(:recipe, :recipe_id, :category, `enter code here`:fruits, :nuts, :cereal, :milk)
end
end
And the response is all nulls but something gets created:
{
"id": 32,
"recipe": null,
"fruits": null,
"nuts": null,
"cereal": null,
"milk": null,
"created_at": "2014-09-29T06:11:39.874Z",
"updated_at": "2014-09-29T06:11:39.874Z"
}
The log looks like:
Unpermitted parameters: recipe
(0.2ms) BEGIN
SQL (0.6ms) INSERT INTO "onboardings" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2014-09-28 23:11:39.874650"], ["updated_at", "2014-09-28 23:11:39.874650"]]
(2.1ms) COMMIT
Rendered onboardings/show.json.jbuilder (0.4ms)
Completed 201 Created in 126ms (Views: 5.5ms | ActiveRecord: 9.6ms)
Any direction is appreciated! Totally lost after looking through all relevant SO posts.
The key of your POST data is recipe, but your onboarding_params is
params.require(:onboarding)
In order to do the strong params correctly I think that would need to be something like
params.require(:recipe).permit(:recipe_id, :Category)
Related
Ive been trying to wrap my head around this and find a solution but I feel like Ive hit a stump. Im trying to grab the first, second, or third photo from my SQL database and feed it into my bootstrap carousel on my homepage. This is my code for my photos controller:
class PhotosController < ApplicationController
before_action :set_photo, only: [:show, :edit, :update, :destroy]
# GET /photos
# GET /photos.json
def index
#photos = Photo.all
end
# GET /photos/1
# GET /photos/1.json
def show
end
def show_first
#photos = Photo.find(1)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_second
#photos = Photo.find(2)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_third
#photos = Photo.find(3)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_image
#photos = Photo.find(params[:id])
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
# GET /photos/new
def new
#photo = Photo.new
end
# GET /photos/1/edit
def edit
end
# POST /photos
# POST /photos.json
def create
#photo = Photo.new(photo_params)
respond_to do |format|
if #photo.save
format.html { redirect_to #photo, notice: 'Photo was successfully created.' }
format.json { render :show, status: :created, location: #photo }
else
format.html { render :new }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /photos/1
# PATCH/PUT /photos/1.json
def update
respond_to do |format|
if #photo.update(photo_params)
format.html { redirect_to #photo, notice: 'Photo was successfully updated.' }
format.json { render :show, status: :ok, location: #photo }
else
format.html { render :edit }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /photos/1
# DELETE /photos/1.json
def destroy
#photo.destroy
respond_to do |format|
format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_photo
#photo = Photo.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def photo_params
params.require(:photo).permit(:title, :medium, :description, :file)
end
end
Ive been looking up and trying to find a good and simple way to accomplish this. And have tried to use the methods like show_first, second, etc. But Im not sure if I am even implementing it right. Would any be able to shed some light on this or at least point me in the right direction? Is the image/* right? Im basically doing my learning on my own and any help and thorough explanation would be awesome and greatly appreciated!
Why not just do it in the show action?
# GET photos/:id
# GET photos/:id.jpg
def show
#photo = Photo.find(params[:id])
respond_to do |format|
format.html {}
format.jpg do
send_data #photos.image, type: 'image/jpeg', disposition: 'inline'
end
end
end
You can then display the photos by:
<% Photo.order(created_at: :desc).limit(10).each do |photo| %>
<%= tag :img, src: path_for(photo, format: :jpg) %>
<% end %>
My csv file takes upto 26 OR 78 values from the large file and don't import the whole data.
rails console view
irb(main):009:0> Stocking.count
(0.0ms) SELECT COUNT(*) FROM "stockings"
=> 26
irb(main):010:0> Stocking.delete_all
SQL (109.4ms) DELETE FROM "stockings"
=> 26
irb(main):011:0> Stocking.count
(0.0ms) SELECT COUNT(*) FROM "stockings"
=> 78
irb(main):012:0> Stocking.delete_all
SQL (62.5ms) DELETE FROM "stockings"
=> 78
irb(main):013:0> Stocking.count
(0.0ms) SELECT COUNT(*) FROM "stockings"
=> 26
As I checked through the rails console with count command.
index.html.erb
<h2>Import Stock File</h2>
<%= form_tag import_stockings_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
stockings_controller.rb
class StockingsController < ApplicationController
before_action :set_stocking, only: [:show, :edit, :update, :destroy]
# GET /Stockings
# GET /deldetails.json
def index
#stockings = Stocking.all
end
def import
Stocking.import(params[:file])
redirect_to stockings_url, notice: "Stockings imported."
end
# GET /Stockings/1
# GET /Stockings/1.json
def show
end
# GET /Stockings/new
def new
#stocking = Stocking.new
end
# GET /stockings/1/edit
def edit
end
# POST /Stockings
# POST /Stockings.json
def create
#stocking = Stocking.new(stocking_params)
respond_to do |format|
if #stocking.save
format.html { redirect_to #stocking, notice: 'Stocking was successfully created.' }
format.json { render :show, status: :created, location: #stocking }
else
format.html { render :new }
format.json { render json: #stocking.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /Stockings/1
# PATCH/PUT /stockings/1.json
def update
respond_to do |format|
if #stocking.update(stocking_params)
format.html { redirect_to #stocking, notice: 'Stocking was successfully updated.' }
format.json { render :show, status: :ok, location: #stocking }
else
format.html { render :edit }
format.json { render json: #stocking.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stockings/1
# DELETE /stockings/1.json
def destroy
#stocking.destroy
respond_to do |format|
format.html { redirect_to stockings_url, notice: 'Stocking was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_stocking
#stocking = Stocking.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def stocking_params
params.require(:stocking).permit(:season, :category, :articleno, :description, :color, :quantity, :rprice, :tamount, :cartonno )
end
end
stocking.rb
class Stocking < ActiveRecord::Base
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
puts row.inspect
end
end
end
application.rb
require File.expand_path('../boot', __FILE__)
require 'csv'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Stock
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.middleware.use 'Utf8Sanitizer'
end
end
routes.rb
Rails.application.routes.draw do
root 'stockings#index'
resources :stockings do
collection { post :import }
end
end
I would like to import all the data into my sqlite3 database.
Any suggestions are most welcome.
Thank you in advance.
The real problem was lying with my uploading file as it was not in correct format that is it was not normalized.
I'm new to rails and I've looked around and none of the solutions on here I've found seem to work. I feel that I am missing something crucial.
I am trying to render a partial from /views/names/_form.html.erb into another file with a different controller /views/posts/index.html.erb. I keep getting the following error.
app/views/names/_form.html.erb where line #1 raised:
First argument in form cannot contain nil or be empty
Extracted source (around line #1):
<%= form_for(#name) do |f| %>
<% if #name.errors.any? %>
<%= pluralize(#name.errors.count, "error") %> prohibited this >name from being saved:
My HTML code is as follows:
<div class="modal" id="myModal">
<h1>Company Name</h1>
<div class="modal-body">
<%= render :partial => '/names/form' %>
...etc...
My Names controller is as follows:
class NamesController < ApplicationController
before_action :set_name, only: [:show, :edit, :update, :destroy]
def index
#names = Name.all
end
def show
end
def new
#name = Name.new
end
def edit
end
def create
#name = Name.new(name_params)
respond_to do |format|
if #name.save
format.html { rredirect_to #name, notice: 'Post created' }
format.json { render :show, status: :created, location: #name }
else
format.html { render :new }
format.json { render json: #name.errors, status: :unprocessable_entity }
end
end
end
My Posts controller is as follows:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index]
# before_filter :first_time_visiting?
# GET /posts
# GET /posts.json
def index
#posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
#posts = Post.all
end
# GET /posts/new
def new
#post = current_user.posts.build
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.build(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
And finally this is my routes file
Rails.application.routes.draw do
resources :posts
devise_for :users
resources :names
root 'index#home'
get "about" => 'index#about'
get "contact" => 'index#contact'
get 'closings' => 'index#closings'
get 'signin' => 'users#sign_in'
Thank you so much for your help.
Add the following line in your post/index method. when to render the partial in your view html , your form try to find the #name object which not found in the post/index method . So we need to initialise #name with new Name object.
def index
#posts = Post.all
#name = Name.new
end
Having a problem with a select box in my edit view in (Rails 4 Ruby 2.2) App.
the select box looks as follows:
<%= f.select(:primary_type, options_for_select([['RESIDENT - COMPLAINT',
'RESIDENT - COMPLAINT'], ['THEFT', 'THEFT'], ['PROPERTY DAMAGE', 'PROPERTY
DAMAGE'], ['DOORS / WINDOWS BROKEN', 'DOORS / WINDOWS BROKEN'], ['WATER LEAKING',
'WATER LEAKING'], ['FLOODING', 'FLOODING'],['ACCIDENT - PERSONAL INJURY',
'ACCIDENT - PERSONAL INJURY'], ['ACCIDENT - VEHICLE', 'ACCIDENT - VEHICLE'],
['ACCIDENT - OTHER', 'ACCIDENT - OTHER'], ['FENCES / GATES BROKEN', 'FENCES /
GATES BROKEN'], ['SUSPICIOUS ACTIVITY - PERSON', 'SUSPICIOUS ACTIVITY - PERSON'],
['SUSPICIOUS ACTIVITY - VEHICLE', 'SUSPICIOUS ACTIVITY - VEHICLE'], ['VANDALISM -
REPORTING', 'VANDALISM - REPORTING'], ['VANDALISM - IN PROGRESS', 'VANDALISM - IN
PROGRESS'], ['HAZZARD REPORT - SAFETY', 'HAZZARD REPORT - SAFETY'], ['HAZZARD
REPORT - FIRE', 'HAZZARD REPORT - FIRE'], ['FIRE - ACTIVE', 'FIRE - ACTIVE'],
['PARKING COMPLAINT - RESIDENT', 'PARKING COMPLAINT - RESIDENT'], ['PARKING
COMPLAINT - VISITOR', 'PARKING COMPLAINT - VISITOR'], ['BREAK AND ENTER -
ATTEMPT', 'BREAK AND ENTER - ATTEMPT'], ['BREAK AND ENTER - CONFIRMED', 'BREAK AND
ENTER - CONFIRMED'], ['ALARM PANEL - PROBLEMS', ' ALARM PANEL - PROBLEMS'], ['GAS
LEAK', 'GAS LEAK'], ['EXPLOSION', 'EXPLOSION'], ['DAMAGE - WEATHER RELATED',
'DAMAGE - WEATHER RELATED']]), { include_blank: true }, class: 'input-group input-
group-lg', id: 'primary-box')%>
It saves to the DB when selected originally and have confirmed this with Rails Console but have no idea how to get this to display in the select box as the primary value when I go to the edit page.
my controller is as follows:
class CallsController < ApplicationController
before_action :set_call, only: [:show, :edit, :update, :destroy]
# GET /calls
# GET /calls.json
def index
#calls = Call.all
#active_calls = #calls.select{|x| x.status == 'ACTIVE'}
#pending_calls = #calls.select{|x| x.status == 'PENDING'}
end
# GET /calls/1
# GET /calls/1.json
def show
end
# GET /calls/new
def new
#call = Call.new
end
# GET /calls/1/edit
def edit
end
# POST /calls
# POST /calls.json
def create
#call = Call.new(call_params)
respond_to do |format|
if #call.save
format.html { redirect_to #call, notice: 'Call was successfully created.' }
format.json { render :show, status: :created, location: #call }
else
format.html { render :new }
format.json { render json: #call.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /calls/1
# PATCH/PUT /calls/1.json
def update
respond_to do |format|
if #call.update(call_params)
format.html { redirect_to #call, notice: 'Call was successfully updated.' }
format.json { render :show, status: :ok, location: #call }
else
format.html { render :edit }
format.json { render json: #call.errors, status: :unprocessable_entity }
end
end
end
# DELETE /calls/1
# DELETE /calls/1.json
def destroy
#call.destroy
respond_to do |format|
format.html { redirect_to calls_url, notice: 'Call was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_call
#call = Call.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def call_params
params.require(:call).permit(:call_time, :status, :primary_type, :secondary_type, :site, :address, :unit_1, :unit_2, :unit_3, :unit_4, :call_details, :unit_on_scene, :unit_clear, :call_num, :site_id)
end
end
Any help will be much appreciated! Thanks in advance!And if more info is required please let me know and ill put it up here.
If you are asking how to set the default you would follow the answer located in the rails api docs
For example:
<%= f.select(:primary_type, options_for_select([["Text1", "value1"],["Text2","value2"] "value2") %>
Edit:
On the edit page, you should have a variable set in your controller like #call = Call.find(params[:id])
Then in the view you can do:
<%= f.select(:primary_type, options_for_select([<your_values>], #call.primary_type ) %>
Ok so after reading some other posts and diving a bit deeper into this I found the solution and it seems to be working just great.
<%= f.select(:primary_type, options_for_select([['Opt 1', 'Opt 1'],['Opt 2', 'Opt 2']], **:selected => #call.primary_type** )) %>
The call that retrieved and displays the Selected value is between the ** ** Do not add the asterisks to your code..
I have an Ruby on rails source,code now i want to parse the data, and send the data.In my code,it will fetches the name from user and display it,How to parse the data in ROR.
This is my controller.rb code
def index
#hotels = Hotel.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #hotels }
end
end
# GET /hotels/1
# GET /hotels/1.json
def show
#hotel = Hotel.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #hotel }
end
end
# GET /hotels/new
# GET /hotels/new.json
def new
#hotel = Hotel.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #hotel }
end
end
# GET /hotels/1/edit
def edit
#hotel = Hotel.find(params[:id])
end
# POST /hotels
# POST /hotels.json
def create
#hotel = Hotel.new(params[:hotel])
respond_to do |format|
if #hotel.save
format.html { redirect_to #hotel, notice: 'Hotel was successfully created.' }
format.json { render json: #hotel, status: :created, location: #hotel }
else
format.html { render action: "new" }
format.json { render json: #hotel.errors, status: :unprocessable_entity }
end
end
end
# PUT /hotels/1
# PUT /hotels/1.json
def update
#hotel = Hotel.find(params[:id])
respond_to do |format|
if #hotel.update_attributes(params[:hotel])
format.html { redirect_to #hotel, notice: 'Hotel was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #hotel.errors, status: :unprocessable_entity }
end
end
end
# DELETE /hotels/1
# DELETE /hotels/1.json
def destroy
#hotel = Hotel.find(params[:id])
#hotel.destroy
respond_to do |format|
format.html { redirect_to hotels_url }
format.json { head :no_content }
end
end
How to parse these data in ROR using Json
HOw to write parsing json file for these data,how to do that one
**Answer of my question**
This part we have to do in controller
hotelscontroller.erb
respond_to :json, :xml
def index
#hotels = Hotel.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: #hotels.to_json(:only => [ :id, :name ]) }
end
end
view/index.json.erb
[
<% #hotels.each do |hotel| %>
{ 'id': <%= hotel.id %>, 'name': "<%= hotel.name %>" },
<% end %>
]
routes.rb
get 'hotels' => 'hotels#index', :as => 'hotels'
There are many ways:
Create method to_json for each model
Create view named, i.e. hotels/index.json.erb and write JSON code using ERb templating engine
[
<% #hotels.each do |hotel| %>
{ 'id': <%= hotel.id %>, 'name': "<%= hotel.name %>" },
<% end %>
]
Use library like jbuilder (on the bottom of page is list of alternatives to JBuilder)
# hotels/index.json.jbuilder
json.array!(#hotels) do |hotel|
json.id hotel.id
json.name hotel.name
end
You can covert a hash to json by to_json method. For reference please see http://apidock.com/rails/ActiveRecord/Serialization/to_json
for example, if you want to write all hotels to external file.
file = File.open("hotels.txt", "w")
file.puts Hotel.all.to_json
file.close
this will write all hotels in external file hotels.txt